このページはJavaScriptでレンダリングされています。それをレンダリングしてスクラップするにはいくつかの方法があります。
私はそれをセレンで擦ることができます。 まずセレンをインストールします。
sudo pip3 install selenium
は次にドライバを入手
https://sites.google.com/a/chromium.org/chromedriver/downloadsは、WindowsまたはMac上にある場合は、クロム「クロムカナリア」のヘッドレスバージョンを使用することができます。全ての場合において
from bs4 import BeautifulSoup
import dryscrape
url = 'https://www.takealot.com/computers/laptops-10130'
session = dryscrape.Session()
session.visit(url)
respData = session.body()
soup = BeautifulSoup(respData, 'html.parser')
containers = soup.find_all("div", {"class": "p-data left"})
for container in containers:
print(container.text)
print(container.find("span", {"class": "amount"}).text)
出力:
from bs4 import BeautifulSoup
from selenium import webdriver
browser = webdriver.Chrome()
url = ('https://www.takealot.com/computers/laptops-10130')
browser.get(url)
respData = browser.page_source
browser.quit()
soup = BeautifulSoup(respData, 'html.parser')
containers = soup.find_all("div", {"class": "p-data left"})
for container in containers:
print(container.text)
print(container.find("span", {"class": "amount"}).text)
あるいは代替的dryscrapeを使用PyQt5
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWebKit import *
from PyQt5.QtWebKitWidgets import QWebPage
from PyQt5.QtWidgets import QApplication
from bs4 import BeautifulSoup
import sys
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
url = 'https://www.takealot.com/computers/laptops-10130'
r = Render(url)
respData = r.frame.toHtml()
soup = BeautifulSoup(respData, 'html.parser')
containers = soup.find_all("div", {"class": "p-data left"})
for container in containers:
print (container.text)
print (container.find("span", {"class":"amount"}).text)
を使用
Dell Inspiron 3162 Intel Celeron 11.6" Wifi Notebook (Various Colours)11.6 Inch Display; Wifi Only (Red; White & Blue Available)R 3,999R 4,999i20% OffeB 39,990Discovery Miles 39,990On Credit: R 372/monthi
3,999
HP 250 G5 Celeron N3060 Notebook - Dark ash silverNBHPW4M70EAR 4,499R 4,999ieB 44,990Discovery Miles 44,990On Credit: R 419/monthiIn StockShippingThis item is in stock in our CPT warehouse and can be shipped from there. You can also collect it yourself from our warehouse during the week or over weekends.CPT | ShippingThis item is in stock in our JHB warehouse and can be shipped from there. No collection facilities available, sorry!JHBWhen do I get it?
4,499
Asus Vivobook ...
しかし、あなたのURLでテストした結果、毎回結果が再現できないことがわかりました。時々、ページがレンダリングされた後、「コンテナ」にコンテンツがありません。
ありがとうございました。私はそれを試して、それは私にスープのオブジェクト全体を与えるように見えました。私はsoup.prettifyを試してみて、すべてを調べました - 出力全体のどこにもリストへの参照がなく、さらにjavascriptを使っているようです。これは私の外に混乱しています - どのようにリストはスープのオブジェクトに含まれていない可能性がありますか? –
サイトでasync jsを使用してリストを取得し、その結果をページに取り込んだ場合、おそらくクローラはそれを待つことを知らないでしょう。この種のサイトについては、分度器とジャスミンを調べてください。 – BoboDarph