【发布时间】:2021-11-02 17:14:34
【问题描述】:
所以我使用 BeautifulSoup 来抓取代码中的链接。艺术家姓名和链接都很好,但我不确定如何在第二个标签中访问国籍。
代码如下:
import requests
import csv
from bs4 import BeautifulSoup
def findName():
page = requests.get('https://web.archive.org/web/20121007172955/https://www.nga.gov/collection/anB1.htm')
soup = BeautifulSoup(page.text, 'html.parser')
last_links = soup.find(class_='AlphaNav')
last_links.decompose()
f = csv.writer(open('h-artist_lastname.csv', 'w')) # Create a file to write
f.writerow(['Last Name, First Name', 'Nationality', 'Link'])
artist_name_list = soup.find(class_='BodyText')
artist_name_list_items = artist_name_list.find_all('a')
artist_nationality_list_items = artist_name_list.find_all('td')
print(artist_nationality_list_items)
for artist_name in artist_name_list_items:
names = artist_name.contents[0]
#nationalities = artist_nationality_list_items.contents[0]
links = 'https://web.archive.org' + artist_name.get('href')
#print(nationalities)
f.writerow([names, links])
findName()
如果我取消注释 for 循环中的行,我会得到一个运行时错误,这是我所期望的。 print 语句为我提供了这个 Artist_nationality_list_items 的值:
<td><a href="/web/20121007172915/http://www.nga.gov/cgi-bin/tsearch?artistid=32727">Babbitt, Platt D.</a></td>, <td>American, died 1879</td>, ..... <- follows this pattern for every artist
基本上,我想要“美国人,于 1879 年去世”的角色。
【问题讨论】:
-
artist_nationality_list_items[1].text? -
循环需要获取页面上每个艺术家的国籍,而不仅仅是第一个。您的解决方案每次只会获取第二个元素。
-
好的,我没有注意你的代码。我刚刚回答了我会怎么做给你
tr。您正在无序地解析表格两次。您无法知道您正在检索的数据是否匹配:您给Baden, Aiko和Baden, Ken的页面中已经存在一个错误,没有匹配的国籍,并且不会有好的结果。 HedgeHog 的方法很好:逐行读取数据
标签: python html web-scraping beautifulsoup