Python BeautifulSoup 循环表数据

标签 python web-scraping beautifulsoup

这里对 Python 非常陌生。我正在尝试从此页面 this page 捕获一些数据。我正在尝试获取两个列表中捕获的项目名称和项目类型。我稍后可以弄清楚如何将它们连接到一张表中。任何帮助都会很棒!

代码行可以自行工作,但循环对我不起作用。 这成功地生成了两行代码:

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)

这会一遍又一遍地重复第一个 item_name 的值:

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
...

最佳答案

您需要使用find_all(返回列表)而不是find(返回单个元素):

for i, j in zip(item_details.find_all('div', class_='item-details'), item_details.find_all('ul', class_='item-type')):
    print(i.h3.a.text, " - ", j.span.text)

输出为:

Veil of Steel  -  Magic Helm
Leoric's Crown  -  Legendary Helm
Harlequin Crest  -  Magic Helm
The Undead Crown  -  Magic Helm
...

或更易读的格式:

names = item_details.find_all('div', class_='item-details')
types = item_details.find_all('ul', class_='item-type')

for name, type in zip(names, types):
    print(name.h3.a.text, " - ", type.span.text)

关于Python BeautifulSoup 循环表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54238239/

相关文章:

python - 我无法使用 Visual Studio 将 python.dll 构建为静态库 (/MTd)

python - 仅包含时间部分的 DatetimeIndex : is it possible

python - Pandas 合并索引不起作用

python - 值错误: invalid literal for int() with base 10: '-'

python - 使用 beautiful soup 解析 html 表

python - 有没有更简单的方法来分配字典并循环更新?

python - 服务不可用 - urllib 代理不工作

python-3.x - 如何使用 BeautifulSoup 从表中选择特定行?

python 抓取ajax内容

python - 使用 BeautifulSoup 4 和 Python 解析 HTML