javascript - 我如何使用 scrapy 来解析 JS 中的链接?

标签 javascript python web-scraping scrapy

我正在尝试让 scrapy 解析页面上的链接以进行抓取。不幸的是,此页面上的链接包含在 JavaScript onclick 函数中。我想使用 SgmlLinkExtractor 规则来提取链接以解析 JavaScript 并创建 URL 以便在可能的情况下与 callback='parse_item' 一起使用。

这是一个带有 JS 函数的每个链接的例子:

<a onclick="window.open('page.asp?ProductID=3679','productwin','width=700,height=475,scrollbars,resizable,status');" href="#internalpagelink">Link Text</a>

我只需要链接提取器发送到回调 parse_item: http://domain.com/page.asp?ProductID=3679

我将如何编写 CrawlSpider 规则来执行此操作?

如果这不可能,那么最终能够解析在定义的一组起始页面上以这种 JavaScript 链接格式嵌入的所有页面的最佳方法是什么?

谢谢大家

最佳答案

您可以使用 SgmlLinkExtractorattrs 参数.

  • attrs (list) – list of attributes which should be considered when looking for links to extract (only for those tags specified in the tags parameter). Defaults to ('href',)

process_value 参数来自 BaseSgmlLinkExtractor :

  • process_value (callable) – a function which receives each value extracted from the tag and attributes scanned and can modify the value and return a new one, or return None to ignore the link altogether. If not given, process_value defaults to lambda x: x.

所以你会为“onclick”属性的值编写一个解析函数:

def process_onclick(value):
    m = re.search("window.open\('(.+?)'", value)
    if m:
        return m.group(1)

让我们检查一下正则表达式:

>>> re.search("window.open\('(.+?)'",
...           "window.open('page.asp?ProductID=3679','productwin','width=700,height=475,scrollbars,resizable,status');"
...          ).group(1)
'page.asp?ProductID=3679'
>>> 

然后在 Rule 中使用 SgmlLinkExtractor

rules=(
    Rule(SgmlLinkExtractor(allow=(),
                           attrs=('onclick',),
                           process_value=process_onclick),
         callback='parse_item'),
)

关于javascript - 我如何使用 scrapy 来解析 JS 中的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556962/

相关文章:

javascript - jquery SlideDown 而不是 SlideAndPush

javascript - 随机函数在 JavaScript 中不起作用

javascript - 根据文本输入显示/隐藏 div

html - 从 html 网络抓取中提取字符串

python - 如何使用 python beautifulSoup 抓取深层嵌入的链接

javascript - 错误的结果字符串比较 jquery

python - 为什么 count() 方法比 for 循环 python 更快

python - Django 导入导出选择字段

python - 改变 django-allauth render_authentication_error 行为

python - Scrapy 迭代同级节点 - xpath 产生空列表