简体   繁体   English

使用Python运行Javascript(onclick)

[英]Run Javascript with Python (onclick)

How could I run a javascript which I found in a html tag with python? 如何使用python运行在html标记中找到的javascript?

There is a tag in a html which contains javascript which is being run after click (onclick). 在html中有一个标记,其中包含单击(onclick)后正在运行的javascript。

Here is the example: 这是示例:

<span id="Handy2">
    <span class="cust-type">0179... </span>
    <a id="dspphone2" style="cursor: pointer;" class="t-info" onclick="jQuery( Handy2 ).load( '/ajax/detail/displayphonenumber.php?coded=MDE3OS8gNjk2MTA5Mw--&amp;adno=140305860&amp;adsource=quoka+online&amp;catid=36_3210' )" data-trackl="Detail 36_3210">
        anzeigen
    </a>
</span>

What should I do to run it and recieve the code which is visible after click on this button? 我应该怎么做才能运行它并收到单击此按钮后可见的代码?

I'm using mostly BeautifulSoup. 我主要使用BeautifulSoup。

EDIT: I know how to do that using Selenium but it is quite an overkill I think. 编辑:我知道如何使用硒来做到这一点,但我认为这是一个过大的杀伤力。

You can't just run it in Python as it is already mentioned above, you need a JavaScript interpreter. 您不能像上面已经提到的那样仅在Python中运行它,而是需要一个JavaScript解释器。 As it seems to me that you just want to get the data that is loaded with this AJAX call you should do something like this (this is just a sample) 在我看来,您只想获取此AJAX调用加载的数据,您应该执行类似的操作(这只是一个示例)

import urllib2
html = urllib2.urlopen('http://your_site_name.com/ajax/detail/displayphonenumber.php?coded=MDE3OS8gNjk2MTA5Mw--&adno=140305860&adsource=quoka+online&catid=36_3210').read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)

This is just a small XHR Request, which returns in its response the phone number you are looking for. 这只是一个小的XHR请求,它在响应中返回您要查找的电话号码。 Try it yourself: http://www.xxx.de/ajax/detail/displayphonenumber.php?coded=MDE3OS8gNjk2MTA5Mw--&adno=140305860&adsource=quoka+online&catid=36_3210 I would use xpath selectors and regex for getting the values you search. 自己尝试: http ://www.xxx.de/ajax/detail/displayphonenumber.php?coded=MDE3OS8gNNjk2MTA5Mw--&adno=140305860&adsource=quoka+online&catid=36_3210我将使用xpath选择器和regex获取您搜索的值。 Then replace the ';' 然后替换“;” with '&' and request the new url. 与“&”并请求新的网址。

It is not possible to run the JavaScript from python direct. 无法直接从python运行JavaScript。
The best you can do is run selenium and phantomJs for scrapping data. 最好的办法是运行selenium和phantomJs来收集数据。

below link might help you. 以下链接可能会对您有所帮助。 https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/ https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM