python - 使用带有 requests 和 lxml 的 xpath 进行抓取,但遇到问题

标签 python python-requests lxml scrape

当我使用 xpath 使用 lxml 抓取数据时,我不断遇到问题。我想抓取道琼斯指数价格,但是当我用 python 打印出来时,它显示元素跨度为 0x448d6c0。我知道那一定是一 block 内存,但我只想要价格。如何打印价格而不是内存中的位置?

from lxml import html
import requests

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.xpath('//*[@id="site"]/div/div[3]/div/div[3]/div[2]/div/table/tbody/tr[1]/th[1]/div/div/div/span')

#This will create a list of volume:


print (prices)

最佳答案

正如你所说,你得到的生成器只是内存位置。要访问它们,您需要对它们调用一个函数,在本例中,您需要文本 .text

此外,我强烈建议更改您的 XPath,因为它是字面位置并且可能会发生更改。

prices = content.xpath("//div[@id='site']//div[@class='price']//span[@class='push-data ']")
prices_holder = [i.text for i in prices]
prices_holder
 ['25,389.06',
 '25,374.60',
 '7,251.60',
 '2,813.60',
 '22,674.50',
 '12,738.80',
 '3,500.58',
 '1.1669',
 '111.7250',
 '1.3119',
 '1,219.58',
 '15.43',
 '6,162.55',
 '67.55']

还值得注意的是,您只能获取加载时的值。如果您希望价格随价格变化而变化,您可能需要使用 Selenium。

关于python - 使用带有 requests 和 lxml 的 xpath 进行抓取,但遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51637310/

相关文章:

python - 如何从 python 发布到 hipchat

python - Microsoft Graph API 委托(delegate)权限

python - 如何从一个随机网站上抓取所有产品?

python - 身份验证在模块中不可用

python - 使用非拉丁字符串作为键在 Python 中使用 Tuple 进行排序

python - 打包为 OS X .app 时请求中的 SSLError

python - 为什么我的 for 循环会覆盖字典中以前的值? (python3)

python - 如何在考虑带连字符的单词的同时在 Python 中拆分单词?

python - Unicode 该死的 : detwingle crashes on a website

python - lxml Python包将版权符号更改为HTML实体