#抓取PTT八卦版的網頁原始碼(HTML)
import urllib.request as req
url="https://www.ptt.cc/bbs/Gossiping/index.html"
#建立一個Request物件,附加Request Headers 的資訊
request=req.Request(url,headers={
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
})
with req.urlopen(request) as response:
data=response.read().decode("utf-8")
#資料決議
import bs4
root=bs4.BeautifulSoup(data,"html.parser")
titles=root.find_all("div",class_="title")
print(titles)
for title in titles:
if title.a !=None: #如果標題包含 a 標簽(沒有被洗掉),印出來
print(title.a.string)
抓取ptt八卦版的時候,我們會得到一個空的串列,原因是一般網頁在我們訪問時會向我們的瀏覽器中存放一個cookie,在連線的時候cookie會被放到“Request Headers”中被帶出去,但是有的網頁需要通過點擊才會得到這個cookie,所以我們要爬取這些網頁的時候就要手動添加一個點擊得到的cookie發送過去,
我們會看到點擊前的cookie是這個樣子的,
點擊后cookie中會多出一個"over18=1"的內容,所以我們要把他也加到我們的程式中去,
#抓取PTT電影版的網頁原始碼(HTML)
import urllib.request as req
url="https://www.ptt.cc/bbs/Gossiping/index.html"
#建立一個Request物件,附加Request Headers 的資訊
request=req.Request(url,headers={
"cookie":"over18=1",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
})
with req.urlopen(request) as response:
data=response.read().decode("utf-8")
#資料決議
import bs4
root=bs4.BeautifulSoup(data,"html.parser")
titles=root.find_all("div",class_="title")
print(titles)
for title in titles:
if title.a !=None: #如果標題包含 a 標簽(沒有被洗掉),印出來
print(title.a.string)
這樣我們就可以直接爬取ptt八卦版的的標題啦,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/254409.html
標籤:python
