【问题标题】:How to use CSS selectors to retrieve specific links lying in some class using BeautifulSoup?如何使用 CSS 选择器使用 BeautifulSoup 检索位于某个类中的特定链接?
【发布时间】:2014-09-08 04:58:23
【问题描述】:

我是 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')

【问题讨论】:

  • 你真的不需要为你的选择器这么具体,真的。
  • 但是有实际问题吗?代码有效,无效,您期望发生什么?
  • 另外,don't use r.text, use r.content 在这里。
  • @Martijn Pieters 代码不起作用。我希望获得allevents.in/lahore“即将举行的活动”选项卡下列出的所有活动的链接@
  • @MartijnPieters 没有使用 r.content,因为我计划提取一些文本和链接,但目前我无法检索所需的链接

标签: python css css-selectors beautifulsoup firebug


【解决方案1】:

该页面在类和标记的使用方面并不是最友好的,但即便如此,您的 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。见Encoding issue of a character in utf-8

【讨论】:

  • stackoverflow.com/questions/24789094/… @Martijn Pieters 我也问了一个与此类似的问题 我不明白如何选择 CSS 选择器,就像您建议我进行编辑一样,请您指导我如何选择所需的 CSS 选择器?
  • @Flecha:一般来说,尝试使用选择器来选择 just 您正在寻找的标签,然后添加更多上下文(如果这不足以识别对象) ) 独一无二。
  • @Flecha:不要只使用 CSS 选择器,它们并不总是足以唯一地识别某些东西。在这里,我首先选择了 one events-horizontal 元素,因为我们不能轻易地用 CSS 选择那个。
【解决方案2】:
import bs4 , requests

res = requests.get("http://allevents.in/lahore/")
soup = bs4.BeautifulSoup(res.text)
for link in soup.select('a[property="schema:url"]'):
    print link.get('href')

这段代码可以正常工作!!

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2017-01-23
    • 2014-09-07
    • 2018-07-05
    • 1970-01-01
    • 2014-03-01
    • 2020-01-04
    • 2019-09-14
    • 2016-06-06
    相关资源
    最近更新 更多