lxml 返回给我一个列表,但它是空的

lxml returned me a list but it's empty

我试图从这个网站列出所有排名前 1000 的 instagramer 帐户:'https://hypeauditor.com/top-instagram/'。 来自 lxml 的 returns 的列表对于 lxml.html 和 lxml.etree 都是空的。

我试过删除tbody,删除text(),上层xpath,都失败了。 值得注意的是,使用上层 xpath,它确实 return 我做了一些事情,但除了 /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/ 的列表。

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

更简单的方法是使用 pandas。它可以像这样读取简单的 HTML 表没问题。尝试使用以下代码 抓取 整个 table.

import pandas as pd

df = pd.read_html('https://hypeauditor.com/top-instagram/')

您肯定想熟悉 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])

The for loop I use for rows is sourced from this answer

这是使用 nth-of-type 获取该列的更轻量级方法。你应该更快找到它。

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://hypeauditor.com/top-instagram/')
soup = bs(r.content, 'lxml')
accounts = [item.text.strip().split('\n') for item in soup.select('#bloggers-top-table td:nth-of-type(4)')][1:]
print(accounts)