gpt4 book ai didi

Python:BeautifulSoup从div类中提取所有标题文本

转载 作者:行者123 更新时间:2023-12-01 02:20:43 25 4
gpt4 key购买 nike

import requests
from bs4 import BeautifulSoup

res = requests.get('http://aicd.companydirectors.com.au/events/events-calendar')
soup = BeautifulSoup(res.text,"lxml")


event_containers = soup.find_all('div', class_ = "col-xs-12 col-sm-6 col-md-8")

first_event = event_containers[0]
print(first_event.h3.text)

通过使用此代码,我可以提取事件名称,我正在尝试一种循环并提取所有事件名称和日期的方法?我还尝试提取单击“阅读更多”链接后可见的位置信息

最佳答案

event_containers 是一个 bs4.element.ResultSet 对象,它基本上是 Tag 对象的列表。
只需循环 event_containers 中的标签,然后选择 h3 作为标题,div.date 作为日期,然后选择 a对于 URL,例如:

for tag in event_containers:
print(tag.h3.text)
print(tag.select_one('div.date').text)
print(tag.a['href'])

现在,对于位置信息,您必须访问每个 URL 并收集 div.date 中的文本。
完整代码:

import requests
from bs4 import BeautifulSoup

res = requests.get('http://aicd.companydirectors.com.au/events/events-calendar')
soup = BeautifulSoup(res.text,"lxml")
event_containers = soup.find_all('div', class_ = "col-xs-12 col-sm-6 col-md-8")
base_url = 'http://aicd.companydirectors.com.au'

for tag in event_containers:
link = base_url + tag.a['href']
soup = BeautifulSoup(requests.get(link).text,"lxml")
location = ', '.join(list(soup.select_one('div.event-add').stripped_strings)[1:-1])
print('Title:', tag.h3.text)
print('Date:', tag.select_one('div.date').text)
print('Link:', link)
print('Location:', location)

关于Python:BeautifulSoup从div类中提取所有标题文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47968568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com