【问题标题】:Web scrape get drop-down menu data python网页抓取获取下拉菜单数据python
【发布时间】:2019-04-05 02:32:38
【问题描述】:

我正在尝试在网页https://www.nexmo.com/products/sms 中获取所有国家/地区的列表。我看到列表显示在下拉列表中。检查页面后,我尝试了以下代码,但我一定做错了什么。在这里我将不胜感激。

import requests
from bs4 import BeautifulSoup
# collect and parse page
page = requests.get('https://www.nexmo.com/products/sms')
soup = BeautifulSoup(page.text, 'html.parser')
# pull all text from the div
name_list = soup.find(class_ ='dropdown-content')
print(name_list)

【问题讨论】:

  • 也许我只是想念它,但我没有看到那里的任何国家...
  • 国家/地区由来自nexmo.com/static/bundle.js的JavaScript填充

标签: python web-scraping drop-down-menu python-requests


【解决方案1】:

此网页使用 JavaScript 呈现 HTML。你可以用 Selenium 渲染它。首先安装 Selenium。

sudo pip3 install selenium

然后获取驱动程序https://sites.google.com/a/chromium.org/chromedriver/downloads(根据您的操作系统,您可能需要指定驱动程序的位置)

from selenium import webdriver
from bs4 import BeautifulSoup

browser = webdriver.Chrome()
url = ('https://www.nexmo.com/products/sms')
browser.get(url)
html_source = browser.page_source
browser.quit()
soup = BeautifulSoup(html_source, 'html.parser')
for name_list in soup.find_all(class_ ='dropdown-row'):
    print(name_list.text)

输出:

Afghanistan
Albania
...
Zambia
Zimbabwe

更新

或者使用 PyQt5:

在 Ubuntu 上

sudo apt-get install python3-pyqt5
sudo apt-get install python3-pyqt5.qtwebengine

其他操作系统:

pip3 install PyQt5

然后运行:

from bs4 import BeautifulSoup
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView


class Render(QWebEngineView):
    def __init__(self, url):
        self.html = None
        self.app = QApplication(sys.argv)
        QWebEngineView.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.load(QUrl(url))
        self.app.exec_()

    def _loadFinished(self, result):
        self.page().toHtml(self.callable)

    def callable(self, data):
        self.html = data
        self.app.quit()

url = 'https://www.nexmo.com/products/sms'
html_source = Render(url).html
soup = BeautifulSoup(html_source, 'html.parser')
for name_list in soup.find_all(class_ ='dropdown-row'):
    print(name_list.text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多