- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试开发一个可持续的网络抓取脚本,以从网站获取所有产品的列表。产品类别链接位于网页的下拉(或可扩展)元素中。在提取 html 并使用 Beautiful Soup 将其转换为文本之前,我使用 PyQt5 来模拟客户端。
例如,如果您在浏览器上访问网站,则必须单击页面左上角附近的按钮才能打开从屏幕左侧弹出的类别列表(我将将其称为“边栏”)。在每个类别中,单击时都会有一个更具体类别的列表,每个类别都有一个我试图用我的代码获取的链接(我将这些称为“子类别”)。
即使侧栏被隐藏,初始类别列表元素也会出现在我的 Beautiful Soup 中,但子类别元素保持隐藏状态,除非子类别标题展开(因此,它们不会出现在我的汤中).我已通过手动检查 Chrome 浏览器中的元素来确认这一点。这是网页 HTML 的片段,其中包含我自己的评论以帮助解释:
<div aria-label="Fruits & Vegetables" data-automation-id="taxonomy-toggle-Fruits & Vegetables">
<button aria-disabled="false" aria-expanded="false" class="NavSection__sectionBtn___1_cAs" data-
automation-id="nav-section-toggle" tabindex="-1"> #Initial category that contains sub-categories
</button>
<div>
</div> #Contains the links I need, but doesn't populate HTML text unless sub-category element is expanded
</div>
下面是子类别元素展开后的样子:
<div aria-label="Fruits & Vegetables" data-automation-id="taxonomy-toggle-Fruits & Vegetables">
<button aria-disabled="true" aria-expanded="true" class="NavSection__sectionBtn___1_cAs" data-
automation-id="nav-section-toggle" tabindex="-1"> #Initial category that contains sub-categories
</button>
<div>
<ul class>
<li class = "NavSection__sectionLink__rbr40> </li>
<li class = "NavSection__sectionLink__rbr40> </li> #can open each li element up to acquire href link
<li class = "NavSection__sectionLink__rbr40> </li>
</ul>
</div>
</div>
这是我的代码:
import bs4 as bs
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEnginePage
#act as a client via Qt5 to acquire javascript elements from webpage
class Page(QWebEnginePage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebEnginePage.__init__(self)
self.html = ''
self.loadFinished.connect(self._on_load_finished)
self.load(QUrl(url))
self.app.exec_()
def _on_load_finished(self):
self.html = self.toHtml(self.callable)
print("Load Finished")
def callable(self, html_str):
self.html = html_str
self.app.quit()
page = Page("https://grocery.walmart.com")
soup = bs.BeautifulSoup(page.html, 'lxml')
print(soup.prettify())
我知道如果aria-expanded
和 aria-disabled
<button>
的属性子类别 <li>
元素从“False”更改为“True”元素将出现在 HTML 中。我通过 Chrome 浏览器中的手动检查确认了这一点。
我的问题是是否有可能获得 href
来自 <li>
元素?我的假设是我必须编辑 HTML 才能更改 aria
在初始解析后将属性从“False”更改为“True”,然后使用这些更改重新解析 HTML。如果没有,除了 Selenium 之外,还有其他方法可以从网页中获取这些元素吗?我正在尝试使用更精简的方法(不打开浏览器窗口等)。
我可以提供实际的网站 URL 和网页截图来帮助澄清,但不确定这是否被认为是好的做法或 Stack Overflow 是否允许(我是新来的!)。
有关我尝试使用的方法的更多背景信息,请参阅以下内容:
最佳答案
如果您从页面下载 HTML,您会发现几乎整个页面都是使用 javascript 创建的,因此 Beautiful Soup 不是正确的工具,因为它仅用于分析 HTML。在这种情况下,解决方案是使用 runJavaScript()
通过 javascript 实现逻辑。 QWebEnginePage
的方法:
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
class WalmartGroceryPage(QtWebEngineWidgets.QWebEnginePage):
def __init__(self, parent=None):
super().__init__(parent)
self._results = None
self.loadFinished.connect(self._on_load_finished)
self.setUrl(QtCore.QUrl("https://grocery.walmart.com"))
@QtCore.pyqtSlot(bool)
def _on_load_finished(self, ok):
if ok:
self.runJavaScript(
"""
function scraper_script(){
var results = []
self.document.getElementById("mobileNavigationBtn").click();
var elements = document.getElementsByClassName("NavSection__sectionBtn___1_cAs");
for (const element of elements) {
element.click();
var items = [];
var sub_elements = document.getElementsByClassName("MobileNavigation__navLink___2-m6_");
for (const e of sub_elements) {
var d = {"name": e.innerText, "url": e.href};
items.push(d);
}
var data = {"name": element.innerText, "items": items};
results.push(data);
}
return results;
}
scraper_script();
""",
self.results_callback,
)
def results_callback(self, value):
self._results = value
QtCore.QCoreApplication.quit()
@property
def results(self):
return self._results
if __name__ == "__main__":
import sys
import json
# sys.argv.append("--remote-debugging-port=8000")
app = QtWidgets.QApplication(sys.argv)
page = WalmartGroceryPage()
ret = app.exec_()
results = page.results
print(json.dumps(results, indent=4))
输出:
[
{
"items": [
{
"name": "Fall Flavors Shop",
"url": "https://grocery.walmart.com/cp/Flavors%20of%20Fall/9576778812"
},
{
"name": "Baking Center",
"url": "https://grocery.walmart.com/browse?shelfId=3433056320"
},
{
"name": "Peak Season Produce",
"url": "https://grocery.walmart.com/browse?shelfId=4881154845"
},
# ...
关于python - PyQt5 QWebEnginePage - 可以编辑 HTML 以打开下拉列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313185/
我现在已经用 PyQt 做了几个项目,而且我越来越熟悉 Qt 采用的模型/ View 思想流派。我已经将它用于列表和表格 View 之类的东西,它们背后有一个自定义模型来显示和操作数据。我使用委托(d
import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class MainWindow(QMainWindow):
使用下面的示例代码(受 here 的严重影响),右键单击上下文菜单并没有真正正确对齐。 从屏幕截图中可以看出,生成的菜单在鼠标光标上方相当多的位置。我希望菜单的左上角与鼠标指针完全对齐。 有没有办法对
所以我创建了一个自定义上下文菜单,但我想根据某些值将树小部件的某些行中的某些项目灰显。如何禁用菜单上的项目? myUI.setContextMenuPolicy( Qt.CustomContextMe
是否可以禁用 QComboBox在 pyqt 中,就像我们可以在 Win Forms(C#) 中那样做,因为我在 QComboBox 中找不到任何选项手动的。我想启用 QcomboBox仅当管理员登录
我想将 QComboBox 与元组中的“键”和“值”一起使用,该元组类似于 django 模型中使用的元组。例如,我对一个人的性别有以下结构。 SEX_CHOICES = (('M', 'Male')
是否可以让 Altair 或 Vega(-Lite) 渲染到 PyQt 小部件,类似于支持多个后端的 Matplotlib?我知道我可以使用 Qt WebView 小部件来呈现带有 Vega 嵌入的网
在下面的示例代码中(受 here 的影响很大),我希望选择单击单元格的整行而不是单个单元格。如何更改代码以合并它? import re import operator import os import
我正在尝试禁用关闭“x”按钮,并且我认为通过将 DockWidgetFeature 设置为仅可移动和可 float 即可工作。 def CreateDockWidget (self): Pan
我已经按照 Yasin Uludag 的一些有用的在线教程来尝试使用 PyQt(或者更确切地说是 PySide)来创建一个简单的 TreeView ,但是我在使用工具提示时遇到了问题。在以下代码中,工
我正在尝试创建一个场景,我需要从 mousePressEvent 位置画线到最新的鼠标 moveposition 这意味着我需要调用 paintEvent 来自 mousePressEvent ,这可
是Python 3的组合和 PyQt 4受到推崇的?有没有其他选择? 最佳答案 我不明白为什么不,有一个 version available对于正常工作的 Python 3,如果你真的需要 Qt,唯一
我正在尝试显示从二进制文件中读取的图像数据(我编写了用于从文件中检索此数据并将其存储为图像以供 QImage() 使用的代码)。我想做的是将 slider 连接到图形 View 小部件,以便当您移动
我已经准备了很多关于如何在 python 和 pyqt 中将多个信号连接到同一个事件处理程序的帖子。例如,将多个按钮或组合框连接到同一功能。 许多示例展示了如何使用 QSignalMapper 执行此
我有一个 PyQt 主窗口,当用户按下某个按钮时,我需要从中获取一串用户输入。 这是我的用户输入窗口代码: class InputDialog(QtGui.QDialog): ''' t
编辑: 以下 buildout.cfg 用于构建 Qt、PyQt 和 SIP [buildout] parts = pyqt [pyqt] recipe = zc.recipe.cmmi ur
我目前正在开发一个应用程序,该应用程序可以使用 PyQt 访问 sqlalchemy 数据库并将其内容显示到 TableView 或其他一些小部件中。现在为了简单起见,我们只说这是一个电话簿,上面有姓
使用我现在拥有的代码,我可以成功地播放文件中的 .mp3 数据。但是我需要使用 QtCore.QBuffer(不是来自文件)播放相同的数据。当我使用文档的示例时,它会出现意外类型的 QBuffer 错
安装 sip 后,我在尝试安装 PyQt-x11-gpl-4.11 时不断收到这个可爱的错误消息。 mycommandline$ python configure-ng.py --verbose Qu
我正在为一个项目使用 PyQt。但并非突然间我收到一个错误: QPixmap: It is not safe to use pixmaps outside the GUI thread in PyQt
我是一名优秀的程序员,十分优秀!