使用 lxml 和 python 请求进行抓取。
Scraping with lxml and python requests.
好的,我又来了,真的想用 lxml 和 python 来解决这个问题。上次我问一个问题时,我正在使用 xpath,并且必须弄清楚如何在直接 xpath 源本身发生变化的情况下进行更改。我已经编辑了我的代码以尝试使用 class 代替。我一直 运行 遇到问题,因为它会在内存中提取地址而不是我想要的文本。在有人说我想做的事情有一个库之前,这不是关于那个,而是让我理解这段代码。这是我到目前为止所拥有的,但是当我打印出来时出现错误,我可以在 print[0].text
后面添加 [0] 但它仍然没有给我任何信息。任何帮助都会很酷。
from lxml import html
import requests
import time
while True:
page = requests.get('https://markets.businessinsider.com/index/realtime-chart/dow_jones')
content = html.fromstring(page.content)
#This will create a list of prices:
prices = content.find_class('price')
print(prices.text)
time.sleep(.5)
可能是发布的格式问题,但您的 while 循环没有缩进。
试试下面我的代码:
while True:
page = requests.get('https://markets.businessinsider.com/index/realtime-chart/dow_jones')
content = html.fromstring(page.content)
prices = content.find_class('price')
#You need to access the 'text_content' method
text = [p.text_content() for p in prices]
for t in text:
if not t.startswith(r"\"): # Prevents the multiple blank lines
print(t)
time.sleep(0.5)
好的,我又来了,真的想用 lxml 和 python 来解决这个问题。上次我问一个问题时,我正在使用 xpath,并且必须弄清楚如何在直接 xpath 源本身发生变化的情况下进行更改。我已经编辑了我的代码以尝试使用 class 代替。我一直 运行 遇到问题,因为它会在内存中提取地址而不是我想要的文本。在有人说我想做的事情有一个库之前,这不是关于那个,而是让我理解这段代码。这是我到目前为止所拥有的,但是当我打印出来时出现错误,我可以在 print[0].text
后面添加 [0] 但它仍然没有给我任何信息。任何帮助都会很酷。
from lxml import html
import requests
import time
while True:
page = requests.get('https://markets.businessinsider.com/index/realtime-chart/dow_jones')
content = html.fromstring(page.content)
#This will create a list of prices:
prices = content.find_class('price')
print(prices.text)
time.sleep(.5)
可能是发布的格式问题,但您的 while 循环没有缩进。
试试下面我的代码:
while True:
page = requests.get('https://markets.businessinsider.com/index/realtime-chart/dow_jones')
content = html.fromstring(page.content)
prices = content.find_class('price')
#You need to access the 'text_content' method
text = [p.text_content() for p in prices]
for t in text:
if not t.startswith(r"\"): # Prevents the multiple blank lines
print(t)
time.sleep(0.5)