首页 > 解决方案 > 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/ 的列表。

我在网络抓取方面没有真正的经验,所以我可能只是在某个地方犯了一个愚蠢的错误,但是由于没有数据我无法启动我的机器学习模型,我真的很挣扎,请帮助。

标签: pythonhtmlweb-scrapinglxmlxml.etree

解决方案


您肯定会想熟悉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 循环来自这个答案


推荐阅读