Python 获取请求返回与查看源代码不同的 HTML

标签 python selenium web-scraping beautifulsoup phantomjs

我正在尝试从我们自己的 URL 存档中提取同人小说,以便使用 NLTK 库对其进行一些语言分析。然而,每次从 URL 中抓取 HTML 的尝试都会返回除同人小说之外的所有内容(以及我不需要的评论表单)。

首先我尝试使用内置的 urllib 库(和 BeautifulSoup):

import urllib
from bs4 import BeautifulSoup    
html = request.urlopen("http://archiveofourown.org/works/6846694").read()
soup = BeautifulSoup(html,"html.parser")
soup.prettify()

然后我发现了 Requests 库,以及用户代理如何成为问题的一部分,所以我尝试了同样的结果:

import requests
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',
        'Content-Type': 'text/html',
}
requests.get("http://archiveofourown.org/works/6846694",headers=headers,timeout=5).text

然后我发现了 Selenium 和 PhantomJS,所以我安装了它们并再次尝试 - 结果相同:

from selenium import webdriver
from bs4 import BeautifulSoup
browser = webdriver.PhantomJS()
browser.get("http://archiveofourown.org/works/6846694")
soup = BeautifulSoup(browser.page_source, "html.parser")
soup.prettify()

我是不是在这些尝试中做错了什么,或者这是服务器的问题?

最佳答案

如果您需要完整的页面源代码以及执行的所有 JavaScript 和发出的异步请求,最后一种方法是朝着正确方向迈出的一步。你只是错过了一件事——你需要 give PhantomJS time在阅读源代码之前加载页面(双关语)。

并且,您还需要单击“继续”以表示您同意查看成人内容:

from bs4 import BeautifulSoup

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


driver = webdriver.PhantomJS()
driver.get("http://archiveofourown.org/works/6846694")

wait = WebDriverWait(driver, 10)

# click proceed
proceed = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Proceed")))
proceed.click()

# wait for the content to be present
wait.until(EC.presence_of_element_located((By.ID, "workskin")))

soup = BeautifulSoup(driver.page_source, "html.parser")
soup.prettify()

关于Python 获取请求返回与查看源代码不同的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38230605/

相关文章:

python - 单元测试 - 用 StringIO 对象替换文件路径

python - ML 引擎实验 eval tf.summary.scalar 未显示在张量板中

java - Selenium WebDriver 在线程 "main"org.openqa.selenium.ElementNotInteractableException 中抛出异常

node.js - 在NodeJS中制作点击事件

css - 如何使用rvest中的节点和类提取网页数据

python - 并行抓取数据+批处理

python - 使用 python 脚本将 Jpg 图像转换为 DCM 图像

python - 找不到 postgresql 9 plpython2.dll

java - 选择表格的项目?用 Selenium

selenium - 如何在 Selenium IDE 中自动化鼠标滚动事件