【发布时间】:2016-06-22 04:12:22
【问题描述】:
您好,我正在阅读“Web Scraping with Python (2015)”。我看到了以下两种打开url的方式,使用.read()和不使用.read()。见bs1和bs2
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://web.stanford.edu/~zlotnick/TextAsData/Web_Scraping_with_Beautiful_Soup.html')
bs1 = BeautifulSoup(html.read(), 'html.parser')
html = urlopen('http://web.stanford.edu/~zlotnick/TextAsData/Web_Scraping_with_Beautiful_Soup.html')
bs2 = BeautifulSoup(html, 'html.parser')
bs1 == bs2 # true
print(bs1.prettify()[0:100])
print(bs2.prettify()[0:100]) # prints same thing
那么.read() 是多余的吗?谢谢
Web scpraing with python p7 上的代码:(使用.read())
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read())
p15 上的代码(不含.read())
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html)
【问题讨论】:
-
除了上面的答案,我建议你尝试使用 requests 库来处理 HTTP 请求 docs.python-requests.org/en/latest 你会更好地控制 HTTP 响应
-
谢谢@A.Romeu 你能给我推荐一些帖子以获取更多信息吗?我确实需要在下一步中调整表格并获取响应网页,我计划在其中使用
mechanize -
在我发给你的链接上,有很多关于如何使用它的信息,在“用户指南”部分。可以直接用docs.python-requests.org/en/latest/user/quickstart/…开始
标签: python beautifulsoup urllib