动态JS在刮取si时生成的代码

2024-04-23 20:16:33 发布

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

我是个新手。我试图用按钮立即购买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)

这种方法不好,因为它需要太多的时间来刮。我也尝试了Selenium方法,但目前也不需要这种方法。
你们能建议我更好的方法来获取价值吗?Here is what I need。 任何帮助都将不胜感激。谢谢。你知道吗



注:我尝试了这个库,因为内容是动态生成的。你知道吗


Tags: 方法textfromimportselfappurldef
1条回答
网友
1楼 · 发布于 2024-04-23 20:16:33

我不确定您的性能会有多大差异,但您可以尝试检查此解决方案。你知道吗

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']}")

在这段代码中,首先我将获得“runescape2007”的id,以防网站所有者更改它。如果您确信值“345”不会更改,则可以跳过该步骤,直接将值“345”作为id提供给下一个post请求。你知道吗

正如你提到的,这个价格是用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请求。在右边,您可以看到对URL的POST请求,在底部您还可以找到发送到POST请求的数据。还要注意的是,在对这个请求的响应中,它总是以1个单位的价格进行回复,因此如果网站上的默认单位数大于1(如下面截图中的5个),则可能不匹配。你知道吗

enter image description here

相关问题 更多 >