lxml-html 读取产生空列表Python 3.6.4

lxml-html read produces empty list Python 3.6.4

我正在尝试从这个 link 读取 STRaND-1 的两个线元素:http://celestrak.com/NORAD/elements/cubesat.txt,这样我就可以从我正在建造的地面站跟踪它。我真的不明白如何使用 xtree.xpath 命令,我想学习如何使用。 我正在尝试使用前段时间从此处提出的类似问题中找到的以下代码:

import numpy as np
from lxml import html
import requests
line_number = 50
for word in range(0,5):
    page = requests.get("http://celestrak.com/NORAD/elements/cubesat.txtid=%s" % word)
    tree = html.fromstring(page.text)
    print (tree.xpath("//b/text()")

这应该打印 html 页面元素之间的代码吧?我如何只从某一行打印?特别是当我想要的文本之前没有 html 前缀时?

感谢您的宝贵时间。

在 Andersson 的帮助下,我想出了如何做到这一点。 (感谢一百万!)

使用 urllib.request.urlopen,一个基本的 for 循环和 .decode utf-8 我让它工作了。甚至不需要 lxml。我知道这远非此逻辑的最优雅实现,任何关于如何清理和压缩它的输入都将不胜感激,但至少它对我有用。

我的代码:

from urllib.request import urlopen


line_number1 = 50
line_number2 = 1

with urlopen("http://celestrak.com/NORAD/elements/cubesat.txt") as TLEDB:
    i = 1
    for line in TLEDB:
        if i == line_number1:
            break
        i += 1
    line1 = line.decode("utf-8")
    print(line1)

    n = 1
    for line in TLEDB:
        if n == line_number2:
            break
        n += 1
    line2 = line.decode("utf-8")
    print(line2)

再次感谢您的帮助。

L

尝试以下解决方案以获取所需数据:

import requests

url = "http://celestrak.com/NORAD/elements/cubesat.txt"
response = requests.get(url)

page_content = response.text
all_lines = [line.strip() for line in page_content.split("\n")]
for index, line in enumerate(all_lines):
    if line == "STRAND-1":
        first_value = all_lines[index + 1]
        second_value = all_lines[index + 2]
        break

print(first_value, "\n", second_value)

输出:

1 39090U 13009E   18037.58367953  .00000016  00000-0  21168-4 0  9998 
 2 39090  98.5328 245.5663 0008674 331.4360  28.6349 14.35009671259097