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

2024-10-04 05:32:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从这个网站上列出所有排名前1000位的instagramer账户:“https://hypeauditor.com/top-instagram/”。 从lxml返回的列表对于两者都是空的lxml.html文件以及lxml.etree文件. 你知道吗

我试图删除tbody、delete 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/的列表。你知道吗

我不是真正有经验的网页抓取,所以有可能我刚刚犯了一个愚蠢的错误,但由于没有数据,我无法启动我的机器学习模型,我真的很挣扎,请帮助。你知道吗


Tags: 文件texthttpscomid列表tophtml
3条回答

更简单的方法是使用pandas。它可以像这样读取简单的HTML表。请尝试以下代码来废弃整个表。你知道吗

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类型来获取该列。你应该快点找到。你知道吗

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)

相关问题 更多 >