【问题标题】:CSS selectors to be used for scraping specific links用于抓取特定链接的 CSS 选择器
【发布时间】:2014-09-07 11:19:47
【问题描述】:

我是 Python 新手,正在从事一个抓取项目。我正在使用 Firebug 复制所需链接的 CSS 路径。我正在尝试从http://kiascenehai.pk/ 收集“即将举行的活动”选项卡下的链接,但这只是为了了解如何获取指定的链接。

我正在寻找解决此问题的方法以及有关如何使用 CSS 选择器检索指定链接的建议。

from bs4 import BeautifulSoup
import requests

url = "http://kiascenehai.pk/"

r  = requests.get(url)

data = r.text

soup = BeautifulSoup(data)

for link in soup.select("html body div.body-outer-wrapper div.body-wrapper.boxed-mode div.main-     outer-wrapper.mt30 div.main-wrapper.container div.row.row-wrapper div.page-wrapper.twelve.columns.b0 div.row div.page-wrapper.twelve.columns div.row div.eight.columns.b0 div.content.clearfix section#main-content div.row div.six.columns div.small-post-wrapper div.small-post-content h2.small-post-title a"):
    print  link.get('href')

【问题讨论】:

  • 你能帮我修复并学习如何获得有用的 css 选择器吗? @Martijn Pieters
  • 您正在加载的 URL 要求选择一个城市http://kiascenehai.pk/select_city?url=http%3A%2F%2Fkiascenehai.pk%2F,并且不包含对我来说即将发生的事件。例如,当我选择“拉合尔”时,设置了一个 cookie。您需要确保 requests 也这样做。
  • @MartijnPieters 如何实现?

标签: python beautifulsoup scrape


【解决方案1】:

首先,该页面需要进行城市选择(在 cookie 中)。使用Session object 来处理这个问题:

s = requests.Session()
s.post('http://kiascenehai.pk/select_city/submit_city', data={'city': 'Lahore'})
response = s.get('http://kiascenehai.pk/')

现在响应得到了实际的页面内容,而不是重定向到城市选择页面。

接下来,让您的 CSS 选择器不要超过所需的大小。在这个页面中没有太多可做的,因为它使用网格布局,所以我们首先需要放大正确的行:

upcoming_events_header = soup.find('div', class_='featured-event')
upcoming_events_row = upcoming_events_header.find_next(class_='row')

for link in upcoming_events_row.select('h2 a[href]'):
    print link['href']

【讨论】:

  • 你能解释一下你为什么在这里使用 .find_next 方法吗?它实际上是为了什么? @Martijn Pieters
  • @Flecha:见the .find_next() documentation;它扫描元素树以查找请求的元素,但不搜索整个文档,仅在起点之后
  • @Flecha:所以它就像一个普通的find,但它不看upcoming_events_header元素之前的任何东西。
  • @Flecha:非常感谢接受,顺便说一句。其他答案中的代码是否也适合您?
【解决方案2】:

这是联合创始人 KiaSceneHai.pk;请不要抓取网站,收集数据需要付出很多努力,我们通过我们的 API 提供访问权限,您可以使用联系表请求访问权限,ty

【讨论】:

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