python - 使用python requests和beautiful soup拉取文本

标签 python python-requests beautifulsoup

感谢您查看我的问题。我想知道是否有任何方法可以从本文中提取数据站点 key ...这是页面的 url https://e-com.secure.force.com/adidasUSContact/

<div class="g-recaptcha" data-sitekey="6LfI8hoTAAAAAMax5_MTl3N-5bDxVNdQ6Gx6BcKX" data-type="image" id="ncaptchaRecaptchaId"><div style="width: 304px; height: 78px;"><div><iframe src="https://www.google.com/recaptcha/api2/anchor?k=6LfI8hoTAAAAAMax5_MTl3N-5bDxVNdQ6Gx6BcKX&amp;co=aHR0cHM6Ly9lLWNvbS5zZWN1cmUuZm9yY2UuY29tOjQ0Mw..&amp;hl=en&amp;type=image&amp;v=r20160921114513&amp;size=normal&amp;cb=ei2ddcb6rl03" title="recaptcha widget" width="304" height="78" role="presentation" frameborder="0" scrolling="no" name="undefined"></iframe></div><textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid #c1c1c1; margin: 10px 25px; padding: 0px; resize: none;  display: none; "></t

这是我当前的代码

    import requests 
from bs4 import BeautifulSoup

headers = {
    'Host' : 'e-com.secure.force.com',
    'Connection' : 'keep-alive',
    'Upgrade-Insecure-Requests' : '1',
    'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64)',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding' : 'gzip, deflate, sdch',
    'Accept-Language' : 'en-US,en;q=0.8'
}
url = 'https://e-com.secure.force.com/adidasUSContact/'
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r, 'html.parser')
c = soup.find_all('div', attrs={"class": "data-sitekey"})
print c

最佳答案

好的,现在我们有了代码,它很简单:

import requests
from bs4 import BeautifulSoup


soup = BeautifulSoup(requests.get("https://e-com.secure.force.com/adidasUSContact/").content, "html.parser")

key = soup.select_one("#ncaptchaRecaptchaId")["data-sitekey"]

data-sitekey 是一个属性不是 css 类,因此您只需要从元素,您可以通过它的 id 找到该元素,如上所示。

你也可以使用类名:

# css selector
key = soup.select_one("div.g-recaptcha")["data-sitekey"]
# regular find using class name
key = soup.find("div",class_="g-recaptcha")["data-sitekey"]

关于python - 使用python requests和beautiful soup拉取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39757805/

相关文章:

post - 为什么我的 Flask 请求对象总是空的?

python - Websocket 到 Python 中的可用数据 - 从 GDAX websocket feed 获取价格

python - 导入 Pandas 会出现错误 AttributeError : module 'pandas' has no attribute 'core' in iPython Notebook

python - 如何覆盖请求中的 .get() 方法?

asynchronous - python-requests 是否支持 HTTP2 和异步调用?

python - 使用 beautiful soup 来模拟页面点击访问页面上的所有 HTML?

Python BeautifulSoup 在写入文件时创建奇怪的\xe2 unicode 字符

python - 如何使用 BeautifulSoup 从 protected 重定向网站获取 html 内容?

python - 请求中的大写 URL 返回 "Name does not resolve"

python - IDLE 无法打开 .py 文件,它提示 "The file' 的编码对于 Python 3.x 无效。”