我在 Selenium 的帮助下编写了一个 Scrapy 蜘蛛来处理网页上的 Javascript 内容。然而,我意识到这个蜘蛛比普通的 Scrapy Crawler 慢得多。
出于这个原因,我想结合两个蜘蛛:常见的 CrawlSpider
用于获取所有资源和仅用于广泛使用 Javascript 的页面的 Selenium Spider。我创建
尝试检测网页是否需要 Javascript 并大量使用它的流水线步骤。迄今为止
我对处理步骤的想法失败了:
- 一些页面使用常见的
<noscript>
标签。 - 一些页面会打印一条警告消息,例如
<div class="yt-alert-message" >
. - ...
表明页面需要 Javascript 的方式有很多种!
- 你知道我如何“检测”广泛使用的页面的标准化方法吗 Javascript?
注意:我只想在真正需要的时候用我的 Selenium Spider 处理页面 因为爬虫速度明显较慢,而且一些页面仅将其用于漂亮的设计。
最佳答案
您可以从脚本标签中获取所有 JavaScript,将其全部加起来,并检查长度是否不超过您认为构成“大量”JavaScript 的任何数量。
# get all script tags
scripts = browser.find_elements_by_tag_name("script")
# create a string to add all the JS content to
javaScriptChars = "";
# create an list to store urls for external scripts
urls = list()
# for each script on the page...
for script in scripts
# get the src
url = script.get_attribute("scr")
# if script is external (has a 'src' attribute)...
if url.__len__() > 0:
# add the url to the list (will access it later)
urls.append(url)
else:
# the script is inline - so just get the text inside
javaScriptChars = javaScriptChars + script.getAttribute("textContent");
# for each external url found above...
for url in urls
# open the script
driver.get(url)
# add the content to our string
javaScriptChars = javaScriptChars + driver.page_source
# check if the string is longer than some threshold you choose
if javaScriptChars.__len__() > 50000:
# JS contains more than 5000 characters
数量是任意的。我猜不到 50000 个字符的 JS 实际上可能不是“很多”,因为页面可能不会每次都调用每个函数。这可能在某种程度上取决于用户的行为。
但是如果您可以假设一个设计良好的站点只包含必要的脚本,那么字符数仍然可以作为它运行多少 JS 的相关指标。
关于javascript - 如何检测页面是否大量使用 Javascript 和 Python、Scrapy 和 Selenium?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16515915/