【问题标题】:In Python, use beautiful soup to pull data using list of div ID在 Python 中,使用漂亮的汤使用 div ID 的列表来拉数据
【发布时间】:2021-07-15 01:50:03
【问题描述】:

有一些 Python 经验。对美汤很陌生。

我正在尝试获取一个 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')

【问题讨论】:

    标签: arrays list for-loop beautifulsoup syntax


    【解决方案1】:

    假设IdOne 等是变量,您可以使用带有soup.select_one() 的f-string 构造

    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,而相关联的值在开始时是要在循环期间添加到的相关列表。

    【讨论】:

    • 我喜欢哈希表。汤的语法会从 python 中的普通表改变到使用汤吗? DivIdList= {'IdOne': 'ListName'} print DivIdList[IdOne]
    • 每次只抓取一个项目时使用列表是否有理由?
    • 我正在导入资产名称的 .csv 列表,资产名称插入 URL,然后提取信息。我边走边想,不确定最好的方法。我只有大约一年的 Python 知识。
    猜你喜欢
    • 2019-11-13
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2018-11-03
    • 2013-11-25
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多