我试图使用requests和BeautifulSoup,特别是国家名称和来自本网站的两个字母的国家代码,在表格中刮取一些元素的文本。
下面是我的代码,我已经逐步回过头来:
import requests
import bs4
res = requests.get('https://country-code.cl/')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
for i in range(3):
row = soup.find(f'#row{i} td')
print(row) # printing to check progress for now我曾希望逐行遍历标记,得到这样的字符串(范围超过249)。然而,soup.find()似乎不起作用,只是打印空白列表。然而,soup.select()工作得很好:
for i in range(3):
row = soup.select(f'#row{i} td')
print(row)为什么soup.find()在这里不像预期的那样工作?
发布于 2022-06-07 13:01:55
find期望第一个参数是您正在搜索的DOM元素,它不适用于CSS选择器。
所以你需要:
row = soup.find('tr', { 'id': f"row{i}" })获得具有所需ID的tr。
然后得到两个字母的国家代码,对于第一个a和title: ISO 3166-1 alpha-2 code,并得到它的.text
iso = row.find('a', { 'title': 'ISO 3166-1 alpha-2 code' }).text要获得全名,不需要搜索类名,所以我使用第二个元素,然后我们需要搜索包含国家名称的span:
name = row.findAll('td')[2].findAll('span')[2].text把这一切结合在一起:
import requests
import bs4
res = requests.get('https://country-code.cl/')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
for i in range(3):
row = soup.find('tr', { 'id': f"row{i}" })
iso = row.find('a', { 'title': 'ISO 3166-1 alpha-2 code' }).text
name = row.findAll('td')[2].findAll('span')[2].text
print(name, iso)其中产出:
Afghanistan AF
Åland Islands AX
Albania AL发布于 2022-06-07 13:21:48
find_all() and select()选择一个列表,但find() and select_one()只选择单个元素。
import requests
import bs4
import pandas as pd
res = requests.get('https://country-code.cl/')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'lxml')
data=[]
for row in soup.select('.tablesorter.mark > tbody tr'):
name=row.find("span",class_="sortkey").text
country_code=row.select_one('td:nth-child(4)').text.replace('\n','').strip()
data.append({
'name':name,
'country_code':country_code})
df= pd.DataFrame(data)
print(df)输出:
name country_code
0 afghanistan AF
1 aland-islands AX
2 albania AL
3 algeria DZ
4 american-samoa AS
.. ... ...
244 wallis-and-futuna WF
245 western-sahara EH
246 yemen YE
247 zambia ZM
248 zimbabwe ZW
[249 rows x 2 columns]https://stackoverflow.com/questions/72531567
复制相似问题