python - lxml 给我返回了一个列表,但它是空的
问题描述
我试图从这个网站列出所有前 1000 个 instagramer 的帐户:' https://hypeauditor.com/top-instagram/ '。从 lxml 返回的列表对于 lxml.html 和 lxml.etree 都是空的。
我尝试删除 tbody、删除 text() 和上部 xpath,但都失败了。值得注意的是,使用上层 xpath,它确实给我返回了一些东西,但它几乎是 /n。
我首先尝试了 lxml.etree
market_url='https://hypeauditor.com/top-instagram/'
r_market=requests.get(market_url)
s_market=etree.HTML(r_market)`
file_market=s_market.xpath('//*[@id="bloggers-top-table"]/tr[1]/td[3]/a/text()')
然后我也尝试了lxml.html。
tree=html.fromstring(r_market.content)
result=tree.xpath('//*[@id="bloggers-top-table"]/tr/td/h4/text()')
此外,我尝试了这个 xpath:
s_market.xpath('//*[@id="bloggers-top-table"]/tbody/text()')
它没有给我任何错误。但在所有尝试之后,它仍然给我空列表或一个充满 n/ 的列表。
我在网络抓取方面没有真正的经验,所以我可能只是在某个地方犯了一个愚蠢的错误,但是由于没有数据我无法启动我的机器学习模型,我真的很挣扎,请帮助。
解决方案
您肯定会想熟悉BeautifulSoup包,它允许您在 python 中导航网页的内容。
使用 BeautifulSoup:
import requests
from bs4 import BeautifulSoup
url = 'https://hypeauditor.com/top-instagram/'
r = requests.get(url)
html = r.text
soup = BeautifulSoup(html, 'html.parser')
top_bloggers = soup.find('table', id="bloggers-top-table")
table_body = top_bloggers.find('tbody')
rows = table_body.find_all('tr')
# For all data:
# Will retrieve a list of lists, good for inputting to pandas
data=[]
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele]) # Get rid of empty values
# For just handles:
# Will retrieve a list of handles, only
handles=[]
for row in rows:
cols = row.find_all('td')
values = cols[3].text.strip().split('\n')
handles.append(values[-1])
我用于行的 for 循环来自这个答案
推荐阅读
- angular - 如何将工具提示添加到 Angular 材料步进器
- gcc - arm-linux-gnueabi-gcc 无法编译?
- sql - 识别组在多列 SQL 中具有相同的值
- javascript - 无限滚动加载dom元素,然后将jquery应用于元素?
- python - 处理多个数组
- python - PyCharm 文件大小超出配置限制 (2,56 MB),代码洞察功能不可用
- c# - IContainerBuilder.AddService 在添加 EdmModel 中的 IRouteBuilder OData .Net Core 中不起作用
- java - 按特定顺序合并两个地图
- javascript - 开发过程中 vs 代码扩展中的contributors.configuration 属性
- database - 使用时间范围在多个日志文件中搜索时间戳,但我有大量数据。那么,如何快速提取日志?