【发布时间】:2020-06-06 17:41:04
【问题描述】:
请不要关闭这个问题 - 这不是重复的。我需要使用 Python 请求而不是 Selenium 来单击按钮,如 here
我正在尝试抓取Reverso Context translation examples page。我有一个问题:我只能获得 20 个示例,然后我需要在页面上存在很多次时单击“显示更多示例”按钮才能获得完整的结果列表。可以简单地使用网络浏览器完成,但是如何使用 Python Requests 库来完成呢?
我查看了按钮的 HTML 代码,但找不到 onclick 属性来查看附加到它的 JS 脚本,我不明白我需要发送什么请求:
<button id="load-more-examples" class="button load-more " data-default-size="14px">Display more examples</button>
这是我的 Python 代码:
from bs4 import BeautifulSoup
import requests
import re
with requests.Session() as session: # Create a Session
# Log in
login_url = 'https://account.reverso.net/login/context.reverso.net/it?utm_source=contextweb&utm_medium=usertopmenu&utm_campaign=login'
session.post(login_url, "Email=reverso.scraping@yahoo.com&Password=sample",
headers={"User-Agent": "Mozilla/5.0", "content-type": "application/x-www-form-urlencoded"})
# Get the HTML
html_text = session.get("https://context.reverso.net/translation/russian-english/cat", headers={"User-Agent": "Mozilla/5.0"}).content
# And scrape it
for word_pair in BeautifulSoup(html_text).find_all("div", id=re.compile("^OPENSUBTITLES")):
print(word_pair.find("div", class_="src ltr").text.strip(), "=", word_pair.find("div", class_="trg ltr").text.strip())
注意: 您需要登录,否则只会显示前10个示例,不会显示按钮。您可以使用此真实身份验证数据:
电子邮件: reverso.scraping@yahoo.com
密码:示例
【问题讨论】:
-
你不能用请求来做到这一点stackoverflow.com/a/37167063/8619959
-
它可以简单地使用网络浏览器完成,但是我如何使用 Python Requests 库来做到这一点? 你不能,Requests 不会执行 JavaScript 或类似的东西.
-
这能回答你的问题吗? "Clicking" button with requests
-
在某些情况下(例如这个例子),可以更详细地探索浏览器的行为:获取它发送的请求并尝试使用 Python 请求做同样的事情 当然,但我不会称之为模拟按钮按下。
标签: python web-scraping beautifulsoup python-requests urllib