对Python来说非常陌生。我正试图从这个页面this page捕获一些数据。我试图在两个列表中获取项目名称和项目类型。我以后可以想办法把它们合并到一个表中。任何帮助都太好了!p>
代码行自己工作,但循环对我不起作用。 这将成功生成两行代码:
import urllib
import bs4 as bs
sauce = urllib.request.urlopen('https://us.diablo3.com/en/item/helm/').read()
soup = bs.BeautifulSoup(sauce, 'lxml')
item_details = soup.find('tbody')
print(item_details)
item_name = item_details.find('div', class_='item-details').h3.a.text
print(item_name)
item_type = item_details.find('ul', class_='item-type').span.text
print(item_type)
这会反复重复第一个项目名称的值:
for div in soup.find_all('div', class_='item-details'):
item_name = item_details.find('div', class_='item-details').h3.a.text
print(item_name)
item_type = item_details.find('ul', class_='item-type').span.text
print(item_type)
这是输出:
Veil of Steel
Magic Helm
Veil of Steel
Magic Helm
Veil of Steel
Magic Helm
Veil of Steel
Magic Helm
Veil of Steel
Magic Helm
Veil of Steel
Magic Helm
Veil of Steel
Magic Helm
...
您可以在details部分的一个循环中执行此操作,而不是将它们保存在不同的列表中并进行匹配
输出
这样做有效:
为什么你的代码不起作用:
看起来您的代码没有遍历所有元素,而是不断获取相同的元素(为所有元素查找所有元素)
您需要使用
find_all
(返回列表)而不是find
(返回单个元素):输出为:
或更可读的格式:
相关问题 更多 >
编程相关推荐