【问题标题】:request-html return incorrect page with correct urlrequest-html 返回带有正确 url 的错误页面
【发布时间】:2018-10-01 19:08:16
【问题描述】:

我在 python 3.6 下使用 requests-html 包进行了爬取练习。我尝试了相关网站,但只有一个 poetryfoundation.org, https://www.poetryfoundation.org/poems/browse#page=1&sort_by=recently_added&topics=20 返回了错误的页面。我会详细演示一下。

这里是源代码,代码只是导入 requests-html 并返回包裹在中的诗歌:
从 requests_html 导入 HTMLSession

class Scrapy:
    def __init__(self, session):
        self.session = session

    def request_content(self, url):
        page = self.session.get(url)
        results = page.html.find('div.c-feature')
        a = True
if __name__ == '__main__':
    session = HTMLSession()
    scrapy = Scrapy(session)

    url = 'https://www.poetryfoundation.org/poems/browse#page=1&sort_by=recently_added&topics=20'
    scrapy.request_content(url=url)

无论我在url中更改什么参数,它都会返回一个错误的页面

感谢您的宝贵时间

【问题讨论】:

  • 因为他们使用的是动态数据,
  • @kcorlidy 您能否提供一些有关动态数据的参考资料,或者有什么解决方案可以解决这个问题!谢谢!
  • 使用 selenium 和 webdriver 应该使用 chrome(我喜欢 PhantomJS 但 selenium 不建议这样做)

标签: url web-scraping scrapy python-requests


【解决方案1】:

使用requestsselenium时是不同的页面,因为网站使用javascript处理数据

from selenium import webdriver
import requests
url = 'https://www.poetryfoundation.org/poems/browse#page=1&sort_by=recently_added&topics=20'
if __name__ == '__main__':
    with requests.Session() as ses:
        headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36",
        "Accept": "*/*",
        "Referer": "https://www.poetryfoundation.org/poems/browse",
        "Accept-Encoding": "gzip, deflate, br",
}

        req = ses.get(url,headers=headers)
        A = req.text

    dr = webdriver.PhantomJS()
    dr.get(url)
    B = dr.page_source
    dr.close()
    print(type(A) == type(B))
    print(A == B)
    print(len(A),len(B))

输出

True # type(A) == type(B)
False # A == B
365477 482831

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 2015-07-31
    • 2018-12-26
    • 2012-09-28
    • 2017-04-02
    • 2011-10-24
    • 1970-01-01
    相关资源
    最近更新 更多