2017-04-09 94 views
0

我工作的腳本可以自動比較不同網站上的遊戲價格(instantgaming,G2A等)。以下腳本適用於某些站點,但其他站點不適用。代碼如下所示:WebScraping - BS4只查找標籤

import bs4 
import requests 
res1 = requests.get('https://www.g2a.com/?search=dead%20by%20daylight') 
res1.raise_for_status() 
soup = bs4.BeautifulSoup(res1.text,'html.parser') 
elems = soup.find('div', {'id': 'content-landing'}) 
children = elems.find('div', {'class': 'mp-product-info'}) 
price = children.find('strong', {'class': 'mp-pi-price-min'}) 
price.text.strip() 

的問題是價格變量包含正確的標籤

<strong class="mp-pi-price-min"></strong> 

但它不保存的價格(根據瀏覽器,它應該是這樣的:)

<strong class="mp-pi-price-min">10,16€</strong> 

相反,使用CSS-Selector執行相同的代碼會返回相同的結果。

回答

0

如果您打開Chrome開發者工具或Firebug,您會看到當您請求該頁面時,它會通過XHR調用返回遊戲和價格的服務。

你需要將你不想要的東西分解,解析爲json並獲得結果。

下面是調用的例子:

from bs4 import BeautifulSoup 
import requests 
import re 
import json 

response = requests.get('https://www.g2a.com/lucene/search/filter?jsoncallback=jQuery111002521088376353553_1491736907010&skip=28837%2C28838%2C28847%2C28849%2C28852%2C28856%2C28857%2C28858%2C28859%2C28860%2C28861%2C28862%2C28863%2C28867%2C28868%2C28869%2C29472%2C29473%2C29474%2C29475%2C29476%2C29482%2C29486%2C33104&minPrice=0.00&maxPrice=640.00&cn=&kr=&stock=all&event=&platform=0&search=dead+by+daylight&genre=0&cat=0&sortOrder=popularity+desc&start=0&rows=12&steam_app_id=&steam_category=&steam_prod_type=&includeOutOfStock=false&includeFreeGames=false&_=1491736907012') 
json_object = json.loads('{"data":%s}}' % (response.content.decode("utf-8").replace("jQuery111002521088376353553_1491736907010(", "")[:-2].replace("\'", ""))) 
for game in json_object["data"]["docs"]: 
    print ("Name: %s (Price: %s)" % (game["name"], game["minPrice"])) 

它會打印:

名稱:死了日光STEAM CD-KEY GLOBAL(價格:10.16)

名稱: Dead by Daylight蒸汽CD-KEY LATAM(價格:5)

名稱:Dead by Daylight - 鮮肉和泥漿DLC Steam CD-KEY GLOBAL(價格:4.99)

名稱:死了日光豪華版STEAM CD-KEY GLOBAL(價格:13.99)

名稱:死了日光STEAM CD-KEY RU/CIS(價格:4.95)

名稱:死了日光 - 20世紀80年代的手提箱DLC STEAM CD-KEY GLOBAL(價格:2.99)

名稱:由日光STEAM CD-KEY SEA死(價格:6)

還要注意,你需要改變&search=...部分對於您想要搜索的遊戲(urlencoded)和_=部分來說明當前的unix時間戳。

+0

工作正常,謝謝! – Terrakx