问题:如何使用 CSS 选择器通过 BeautifulSoup 检索位于某个类中的特定链接?

我是 Python 的新手,我正在学习它是为了抓取,我正在使用 BeautifulSoup 来收集链接(即“a”标签的 href)。我正在尝试收集网站http://allevents.in/lahore/的“即将举行的活动”选项卡下的链接。我正在使用 Firebug 来检查元素并获取 CSS 路径,但这段代码没有返回任何内容。我正在寻找解决方法以及一些关于如何选择适当的 CSS 选择器以从任何站点检索所需链接的建议。我写了这段代码:

from bs4 import BeautifulSoup

import requests

url = "http://allevents.in/lahore/"

r  = requests.get(url)

data = r.text

soup = BeautifulSoup(data)
for link in soup.select( 'html body div.non-overlay.gray-trans-back div.container div.row div.span8 div#eh-1748056798.events-horizontal div.eh-container.row ul.eh-slider li.h-item div.h-meta div.title a[href]'):
    print link.get('href')

解答

该页面在类和标记的使用方面并不是最友好的,但即便如此,您的 CSS 选择器也过于具体,无法在此处使用。

如果你想要即将到来的事件,你只想要第一个<div class="events-horizontal">,然后只需抓住<div class="title"><a href="..."></div>标签,所以标题上的链接:

upcoming_events_div = soup.select_one('div.events-horizontal')
for link in upcoming_events_div.select('div.title a[href]'):
    print(link['href'])

请注意,您不应该_使用r.text;使用r.content并将 Unicode 解码留给 BeautifulSoup。参见utf-8 中字符的编码问题

Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐