【问题标题】:Scrape dynamically loaded website抓取动态加载的网站
【发布时间】:2018-04-12 09:41:04
【问题描述】:

当我使用 cURL 加载页面“http://proxydb.net”或尝试抓取页面时,响应正文为空。显然,页面是使用 JavaScript 动态加载的。

仍然加载渲染的源代码的选项是什么?

我尝试通过 Firefox 驱动程序使用 Selenium,但这仅在 15 秒内将我的 CPU 使用率推至 100%。我想这不是一个可行的选择,尤其是对于涉及使用 Selenium 抓取 100,000 多个页面的大型项目而言。

此外,了解动态加载页面的概念。这些是如何工作的?需要什么代码才能使它们工作?

【问题讨论】:

  • 尝试使用 python 和 scrapy-splash 来动态加载页面
  • 您可以尝试使用github.com/MechanicalSoup/MechanicalSoup,我个人没有尝试过,但它可能会有所帮助。如果这不起作用,那么您可能必须采用硒方式。
  • 谢谢。我要试试。使用 Selenium 时,有没有办法让网络浏览器保持打开状态?在我的情况下,浏览器会为每个请求打开然后关闭,这非常消耗我的系统资源。

标签: python curl web-scraping scrapy


【解决方案1】:

When I load the page "http://proxydb.net" using cURL, or try to scrape the page, then the response body is empty - 因为这个特定的网站使用用户代理白名单,如果您的用户代理不在白名单上,您只会得到一个空白页面。据推测,所有主要的网络浏览器都被列入白名单(Chrome、Internet Explorer、Edge、Safari、Opera 等),但这里有一个被列入白名单的特定用户代理:

Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 

(在 windows 7 x64 上运行的 Chrome 65 的用户代理),因此,这是有效的:

curl 'http://proxydb.net/' -H 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'

至于如何动态加载内容,通常使用XMLHttpRequests 或在较旧的代码中,iframe 完成。

Apparently, the page is dynamically loaded using JavaScript. - 错了,这些家伙没有动态加载代理列表,它们直接嵌入到首页(只要您使用的是列入白名单的用户代理),被隐藏为

var q = '42.86.831'.split('').reverse().join('');
var yy = /* */ atob('\x4d\x43\x34\x79\x4d\x54\x67\x3d'.replace(/\\x([0-9A-Fa-f]{2})/g, function() {
    return String.fromCharCode(parseInt(arguments[1], 16))
}));
var pp = (3109 - ([] + [])) /**/ + (+document.querySelector('[data-numr]').getAttribute('data-numr')) - [] + [];
document.write('<a href="/' + q + yy + '/' + pp + '#http">' + q + yy + String.fromCharCode(58) + pp + '</a>');

(在这种情况下,它与 data-numr div 一起转换为 138.68.240.218:3128 - 它实际上是加密的,解密密钥在一个看起来像 &lt;div style="display:none" data-numr="19"&gt;&lt;/div&gt; 的 div 中,这里的密钥是 19。)

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 2018-08-09
    • 2021-04-17
    • 2010-09-17
    • 1970-01-01
    • 2020-10-02
    • 2017-04-13
    相关资源
    最近更新 更多