【发布时间】:2019-07-04 20:28:40
【问题描述】:
我在 python 中创建了一个与 selenium 相关的脚本,以从网页的左侧边栏中刮取位于盒子之类的容器中的一些内容。当我使用硒时,我可以毫无困难地得到它们。现在,我想使用 requests 模块获得相同的内容。我在开发工具中做了一些实验,发现有一个帖子请求正在发送,它会产生一些我在下面粘贴的 json 响应。但是,此时我不知道如何使用请求获取内容。
硒方法:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def get_content(link):
driver.get(link)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#tab-outline"))).click()
for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#pageoutline > [class^='outline_H']"))):
print(item.text)
if __name__ == '__main__':
url = "http://wave.webaim.org/report#/www.onewerx.com"
with webdriver.Chrome() as driver:
wait = WebDriverWait(driver,10)
get_content(url)
脚本产生的部分输出(根据需要):
Marketing Mix Modeling
Programmatic & Modeling
Programmatic is buying digital advertising space automatically, with computers using data to decide which ads to buy and how much to pay for them.
Modern
Efficient
Scalable
Resultative
What is Modeling?
Modeling is an analytical approach that uses historic information, such as syndicated point-of-sale data and companies’ internal data, to quantify the sales impact of various marketing activities.
Programmatic - future of the marketing
尝试处理请求时:
import requests
url = "http://wave.webaim.org/data/request.php"
headers = {
'Referer': 'http://wave.webaim.org/report',
'X-Requested-With': 'XMLHttpRequest'
}
res = requests.post(url,data={'source':'http://www.onewerx.com'},headers=headers)
print(res.json())
我得到以下输出:
{'success': True, 'reportkey': '6520439253ac21885007b52c677b8078', 'contenttype': 'text/html; charset=UTF-8'}
如何使用请求获取相同的内容?
为了更清楚: This is what I'm interested in.
上面的输出看起来与图像不同,因为 selenium 脚本单击附加到该框的以下按钮以展开内容:
【问题讨论】:
-
如果您查看 res.json,它会为您提供有关响应的元数据,例如标头和状态代码以及在您的情况下为
text/html的内容类型。试试 res.text 或 res.content。 -
res.text和res.content产生相同的东西@Himanshu Pant。
标签: python python-3.x web-scraping