从Common中的网页获取数据时出现问题

2024-04-20 01:00:11 发布

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

我用python编写了一个脚本,从一个网站上获取一些数据。看来我做得对。然而,当我打印数据时,我得到一个错误list index out of range。数据在注释中。因此,在我的脚本中,我尝试使用python的内置注释处理方法。有人能指出我哪里出错了吗?你知道吗

网站链接:website_link

到目前为止我试过的脚本:

import requests
from bs4 import BeautifulSoup, Comment

res = requests.get("replace_with_the_above_link")
soup = BeautifulSoup(res.text, 'lxml')
for comment in soup.find_all(string=lambda text:isinstance(text,Comment)):
    sauce = BeautifulSoup(comment, 'lxml')
    items = sauce.select("#tco_detail_data")[0]
    data = ' '.join([' '.join(item.text.split()) for item in items.select("li")])
    print(data)

这是回溯:

Traceback (most recent call last):
  File "C:\Users\Local\Programs\Python\Python35-32\new_line_one.py", line 8, in <module>
    items = sauce.select("#tco_detail_data")[0]
IndexError: list index out of range

请点击下面的链接查看我想获取的数据部分:Expected_output_link


Tags: of数据textin脚本dataindex网站
1条回答
网友
1楼 · 发布于 2024-04-20 01:00:11

所有注释都不包含带有“#tco\u detail\u data”标记的html,因此select返回一个空列表,当您尝试选择第一项时,该列表将引发IndexError。你知道吗

但是,您可以在“ul#tco#detail#data”标记中找到数据。你知道吗

res = requests.get(link)
soup = BeautifulSoup(res.text, 'lxml')
data = soup.select_one("#tco_detail_data")

print(data)

如果你想要data在一个列表中

data = [list(item.stripped_strings) for item in data.select("ul")]

如果你喜欢弦乐

data = '\n'.join([item.get_text(' ', strip=True) for item in data.select("ul")])

相关问题 更多 >