谁请帮帮忙,我想把所有的内容从url转移到一个html文件,有人能帮我吗?我也必须使用用户代理!
发布于 2020-06-16 03:22:41
因为我不知道你需要抓取哪个站点,所以我说几个wasy
如果站点包含JS前端,并且需要加载等待,那么我建议您使用requests_html
模块,它具有渲染内容的方法
from requests_html import HTMLSession
url = "https://some-url.org"
with HTMLSession() as session:
response = session.get(url)
response.html.render() # rendering JS code
content = response.html.html # full content
如果站点不使用JS作为前端内容,那么requests
模块真的是一个很好的选择
import requests
url = "https://some-url.org"
response = requests.get(url)
content = response.content # html content in bytes()
也可以使用python webdriver,但是selenium
的运行速度很慢。
发布于 2020-06-16 02:57:14
欢迎来到SO,当你问一个问题时,你需要提交你已经尝试过的代码,here's where you can learn to ask a question properly.关于你的问题,当你说“我想把所有的内容从url转移到一个html文件”时,我假设你只是想读取页面源代码并将其保存在一个文件中。
import requests as r
from bs4 import BeautifulSoup
data = r.get("http://example.com", headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0')
soup = BeautifulSoup(data.text)
file = open('myfile.html', 'w')
file.writelines(soup)
file.close()
如果你得到一个名为TypeError的错误: write()参数必须是字符串,而不是标签,只需将soup类型转换为字符串。
file.writelines(str(soup))
https://stackoverflow.com/questions/62394852
复制相似问题