如何使用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中的字符编码问题