抓取网站时动态JS生成的代码

时间:2019-03-25 23:34:47

标签: python python-3.x web web-scraping beautifulsoup

我是新手。我正在尝试通过按钮立即购买this site抓取值。
我尝试过的选项是:

from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage

class Client(QWebPage):
    def __init__(self):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        # self.loadFinished.connect(self.on_page_load)
        # self.mainFrame().load(QUrl(url))
        # self.app.exec_()
    def on_page_load(self):
        self.app.quit()
    def mypage(self, url):
        self.loadFinished.connect(self.on_page_load)
        self.mainFrame().load(QUrl(url))
        self.app.exec_()
client_response = Client()
def parse(url):                # OSRS + RS3
    client_response.mypage(url)
    source = client_response.mainFrame().toHtml()
    soup = BeautifulSoup(source, 'html.parser')
    osrs_text = soup.findAll('input', attrs={'type': 'number'})
    quantity = (osrs_text[0])['min']
    final = 0
    if(quantity == '1'):
        final_osrs = round(float(soup.findAll('span', attrs={'id':'goldprice'})[0].text),3)
        print(final_osrs)

    else:
        price = round(float(soup.findAll('span', attrs={'id':'goldprice'})[0].text),3)
        final_rs3 = price/int(quantity)
        print(final_rs3)

这种方法不好,因为它花费了太多时间来抓取。 我也尝试过硒方法,但目前也不需要。
你们能否建议我更好地利用价值的方法? Here is what I need。 任何帮助将不胜感激。谢谢。



附注:我尝试了此库,因为内容是动态生成的。

1 个答案:

答案 0 :(得分:3)

我不确定您将获得多少性能差异,但是您可以尝试并检查此解决方案。

import requests
from bs4 import BeautifulSoup

baseUrl = 'https://www.rsmalls.com/osrs-gold'
postUrl = 'https://www.rsmalls.com/index.php?route=common/quickbuy/rsdetail'

with requests.Session() as session:
    res = session.get(baseUrl)
    soup = BeautifulSoup(res.text, 'lxml')
    game_id = soup.select_one("#choose-game > option[selected]")['value']
    response = session.post(postUrl, data={'game_id': game_id}).json()
    print(f"{'Gold Price:'} {response['price']}")

在此代码中,首先,我获得了“ Runescape 2007”的ID,以防万一网站所有者对其进行了更改。如果您确定它不会更改,则可以跳过该步骤,直接向下一个发布请求提供ID“ 345”作为ID。

价格已包含您提到的JS代码。使用浏览器开发工具,我可以获取实际的POST请求以获取价格,该请求需要从下拉列表中选择ID。对https://www.rsmalls.com/index.php?route=common/quickbuy/rsdetail的POST请求给出了json响应,如:

{"success":true,"product_id":"30730","price":0.85,"server_id":"1661","server_option":"463","quantity":"1|5|10|20|50|100|200|300|500|1000|1500|2000","name":"M"}

因此,我将响应解析为json并从中获取了价格。
如果您有任何问题,请告诉我。

编辑:

https://rsmalls.com/runescape3-gold上发出了不同的POST请求,因此相同的解决方案不起作用。每个页面/网站/数据的POST请求可以不同。 您可以使用浏览器devtools自行找到此类发帖请求,如下所示。在右侧,您可以看到向URL发出了POST请求,在底部,您还将找到发送到POST请求的数据。另请注意,在响应此请求时,它总是以1个单位的价格进行答复,因此,如果网站上的默认单位数大于1(例如下面的屏幕截图中的5),则该价格可能不匹配。

enter image description here