[問題] beautifulsoup 上的 find() takes no key
[問題] beautifulsoup 上的 find() takes no keyword argument 如何解決
請問各位神人
我最近剛開始學習如何用python爬文章於是挑了mobile01當目標
但是遇到了 find() takes no keyword argument不知道如何解決,我上卓查了一些類似的文章說要改成find_all,但是卻返回”str”沒有find_all這個attribute
更何況我只要爬一個特定目標應該不會是find_all才對
以下程式碼
url="https://www.mobile01.com/newtopics.php?mode=newtopic"
mWeb = openpyxl.load_workbook("mobile.xlsx")
ws = mWeb.active
for a in range(1,6):
#建立一個requet物件,附加request Headers 的資訊,用request去打開網址
request=req.Request(url,headers={
"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Mobile Safari/537.36"
})
with req.urlopen(request) as response:
data=response.read().decode("utf-8")
#解析原始碼,取得每篇文章的標題(抓全區熱門文章)
#data是網頁的html原始碼
#root表示整份網頁
root=bs4.BeautifulSoup(data,"html.parser")#data是透過網路抓下來的資料(html原始碼)丟給bs4會用html解析
titleLinks = root.find_all("div",class_="c-articleItem__title")
page = root.find("a",class_="c-pagination c-pagination--next")
for titleLink in titleLinks:
titles = titleLink.a.text
articleLink = "https://www.mobile01.com/" + titleLink.a["href"]
ws.cell(i,1,i)
ws.cell(i,2,titles)
ws.cell(i,3,articleLink)
mWeb.save("mobile.xlsx")
request=req.Request(articleLink,headers={
"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Mobile Safari/537.36"
})
with req.urlopen(request) as response:
inner = response.read().decode("utf-8")
body = inner.find ("div" ,itemprop = "articleBody")
article = body.text
ws.cell(i,6,article)
print(article)
mWeb.save("mobile.xlsx")
i = i+1
n = 1
#抓時間作者資料
titleInfos = root.find_all("div",class_="c-articleItemRemark__wAuto")
for titleInfo in titleInfos:
author = titleInfo.div.a.text
timeInfo = titleInfo.div.next_sibling.text
ws.cell(n,4,author)
ws.cell(n,5,timeInfo)
mWeb.save("mobile.xlsx")
n = n+1
url = "https://www.mobile01.com/" + page["href"]
但我單把那行抓出來開另個檔案request測試卻又可以抓到文章
root=bs4.BeautifulSoup(data,"html.parser")#data是透過網路抓下來的資料(html原始碼)丟給bs4會用html解析
body = root.find("div" , itemprop="articleBody")
article = body.text
print(article)
我不太理解為什麼
先謝過回答的各位了
-----
Sent from JPTT on my Samsung SM-N960F.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 163.22.18.74 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1670951523.A.F7C.html
※ 編輯: livehorse (163.22.18.74 臺灣), 12/14/2022 01:16:19
※ 編輯: livehorse (163.22.18.74 臺灣), 12/14/2022 01:18:02
※ 編輯: livehorse (163.22.18.74 臺灣), 12/14/2022 01:30:47
※ 編輯: livehorse (163.22.18.74 臺灣), 12/14/2022 01:33:00
→
12/14 10:03,
2年前
, 1F
12/14 10:03, 1F
→
12/14 11:24,
2年前
, 2F
12/14 11:24, 2F
Python 近期熱門文章
PTT數位生活區 即時熱門文章