从scrapy中的javascript onclick元素获取url

2024-04-23 10:43:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从onclickjavascript函数获取href url

这是我的按钮元素

<button class="module_bnt" onclick="window.location.href='https://someurl.org/module/'">  Click Here to Start Quiz</button>`

这是我的解析函数

def parse(self, response):
    articles = response.xpath('//article')
    for article in articles:
        id = article.xpath('./@id').get()

        if id is not None:
            id = id.encode('utf-8') # converting to utf-8 and removing u character space in string

            moduleBnt = article.xpath('.//button[@class="module_bnt"]/a/@href').get()

            if moduleBnt is None:
                moduleBnt = article.xpath(".//button[@class="module_bnt"]/a/@onclick").extract_first()

有人能帮我吗?提前谢谢


Tags: to函数inidresponsearticlebuttonxpath
1条回答
网友
1楼 · 发布于 2024-04-23 10:43:21

您可以使用css选择器获取onclick属性值,然后使用正则表达式提取url

大概是这样的:

url = response.css('.module_bnt::attr(onclick)').re('href='(.*)')[0]

希望能有帮助

相关问题 更多 >