嗨,我正在閱讀「使用Python進行網頁搜索(2015)」。我看到了以下兩種打開網址的方式,使用和不使用.read()
。見bs1
和bs2
在urlopen('http .....')。read()中讀取()是做什麼的? [urllib]
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的P7與蟒蛇scpraing:在P15(使用.read()
)
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read())
代碼(不.read()
)
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bsObj = BeautifulSoup(html)
除了上述問題的答案,我建議你嘗試使用圖書館的請求HTTP請求 HTTP: //docs.python-requests.org/en/latest/ 你會更多地控制HTTP響應 –
謝謝@ A.Romeu你能否引薦我一些帖子以獲得更多信息?我需要在下一步中填寫表單並獲取響應網頁,我計劃使用'mechanize' –
在我發送給您的鏈接中,有關如何使用它的許多信息,請參閱「用戶指南」。您可以直接從http://docs.python-requests.org/en/latest/user/quickstart/#make-a-request –