Python get请求返回与view sou不同的HTML

2024-06-10 18:08:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从我们自己的URL的存档中提取fanfiction,以便使用NLTK库对其进行一些语言分析。然而,每次尝试从URL抓取HTML都会返回除了fanfic(和注释表单,我不需要的)之外的所有内容。在

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

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

然后我发现了请求库,以及用户代理是如何成为问题的一部分的,所以我尝试了这个方法,结果是一样的:

^{pr2}$

后来我发现了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()

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


Tags: fromorgimportbrowserhttpparserurlhtml
2条回答

如果您需要完整的页面源代码(包含所有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()

Alexce解释了为什么你的代码没有给你想要的,如果你想要的只是源代码中的文本,如果你添加了参数view_adult=true

import requests
from bs4 import BeautifulSoup
url = "http://archiveofourown.org/works/6846694?view_adult=true"


r= requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
chap = soup.select_one("#chapter-1")
preface = soup.select_one("div.preface.group")


print(preface)
print(chap)

这会给你:

^{pr2}$

希望这就是你所需要的。在

相关问题 更多 >