在Python中,使用beautiful soup使用div ID列表拉取数据

In Python, use beautiful soup to pull data using list of div ID

有一些 Python 经验。对 Beautiful soup 很陌生。

我正在尝试获取汤的 div ID 列表,然后导出

正确的写法是什么?

#my div ID list
DivIdList = [IdOne, IdTwo, IdThree,] 

#to be filled with soup 
ListName = [] 
HostList = []
InfoList = []

#loop through div ID list
for i in DivIdList:

    #when found fill up with soup
    Name = soup.find('IdOne')
    Host = soup.find('IdTwo')
    Info = soup.find('IdThree')

#Soup found to be exported
ListName.append(Name.text)
HostList.append(Host.text)
InfoList.append(Info.text)

#export soup info with headers
df = pd.DataFrame({'All Names':ListOfNames,....}) 
df.to_csv('MyFile.csv', index=False, encoding='utf-8')

假设 IdOne 等是变量,您可以使用带有 soup.select_one()

的 f 字符串构造
soup.select_one(f'#{IdOne}')  # etc 

# 表示一个 id css 选择器。

您将使用 i 作为循环变量;另外,与变量命名保持一致 HostList.

如果 IdOne 是一个 id css 选择器,那么删除 # 并直接使用,例如soup.select_one(i)

然后您需要一种方法来添加到适当的列表中,例如

ListName = [] 
HostList = []
InfoList = []

list_of_lists = [ListName, HostList, InfoList]
DivIdList = [IdOne, IdTwo, IdThree]

for number, i in enumerate(DivIdList):
    list_of_lists[number].append(soup.select_one(f'#{i}').text)

在使用 .text 访问器之前检查 soup.select_one(f'#{i}') is not None 是明智的。

你也可以有一个字典,其中的键是 id,关联的值在开始时是要在循环期间添加到的相关列表。