【问题标题】:Web Scraping, Infinite scrolling and extracting links网页抓取、无限滚动和提取链接
【发布时间】:2017-08-31 14:03:19
【问题描述】:

我正在尝试从“https://www.pakwheels.com/forums/c/travel-n-tours”中提取“Saudi Sim Card”等所有链接。我正在使用 Selenium 网络驱动程序来滚动网页,但我无法提取所有链接。我得到的错误是“None 类型的对象没有 href 属性”有什么建议吗?

from PageScroller import WebPageScroller
import bs4 as bs

sourceUrl='https://www.pakwheels.com/forums/c/travel-n-tours'

#----------------------- Scrolling to the bottom of page and getting source code --------------------------------------#

scrollObject=WebPageScroller
pageSource=scrollObject.getScrolledPageSource(scrollObject,sourceUrl)

# ------------------------------------- Getting links ---------------------------------- #
soup = bs.BeautifulSoup(pageSource, 'lxml')

blogUrls=[]
for url in soup.find_all('a'):

    if((url.get('href').find('/forums/t/')!=-1) and (url.get('href').find('about-the-travel-n-tours-category')==-1) and (url.get('href').find('/forums/t/topic/')==-1)):
        blogUrls.append(url.get('href'))
        print(url.get('href'))       
print(len(blogUrls))

【问题讨论】:

  • 本网站通过发布代码、显示结果和提出特定问题来工作。
  • 我编辑了这个问题。现在更清楚了吗?
  • 我还没有直接上传图片的权限。我只能将图像添加为链接。怎样才能获得这个特权?

标签: python selenium-webdriver web-scraping


【解决方案1】:

使用 Selenium 进行刮擦通常很糟糕,而且您找到处理无限滚动的方法的可能性微乎其微。

这个站点基本上在https://www.pakwheels.com/forums/c/travel-n-tours/l/latest.json?_=<uts> 有一个JSON 端点,其中<uts> 是一个Unix 时间戳。

基本上,这就是它的工作原理。打开 Chrome DevTools 或 Firebug 并加载论坛屏幕。查看Network 标签。有一个名为latest.json?_=1491493915518XHR 文件。点击它。

Request URL 显示为 https://www.pakwheels.com/forums/c/travel-n-tours/l/latest.json?_=1491493915518。这是您的端点。

现在您只需要一个 Unix 时间戳和几行代码:

import requests

current_uts = from_some_unix_timestamp_source  
response = requests.get('https://www.pakwheels.com/forums/c/travel-n-tours/l/latest.json?_={}'.format(current_uts))
print(response.json())

然后您会返回该页面上所有内容的 JSON 表示。如果您使用更新的时间戳重新运行相同的脚本,它将检索新的论坛主题。如果您想检索较旧的线程(或什至抓取整个论坛),您也可以使用旧的 Unix 时间戳回到过去。我将留给您弄清楚如何将其构建成更强大的东西。

【讨论】:

    猜你喜欢
    • 2012-09-13
    • 2023-03-08
    • 2020-02-18
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多