我是網路抓取的新手,無法從以下網站獲取“a”標簽中的 URL 串列:http : //www.tauntondevelopment.org//msip/JHRindex.htm。我得到的只是一個空串列 - 客戶串列:[] 感謝您的幫助!
這是我的代碼:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
# This is the url of one major industrial park that we will be scraping
park_url = "http://www.tauntondevelopment.org//msip/JHRindex.htm"
uPark = uReq(park_url)
park_html = uPark.read()
uPark.close()
park_soup = soup(park_html, "html.parser")
filename = "ParkText.html"
f = open(filename, "w")
f.write(park_soup.prettify())
f.close()
# get a list of the urls of park_url
clients_list = []
for link in park_soup.findAll('li'):
clients_list.append(link.get('href'))
print("clients list:", clients_list)
# write clients to a file
filename = "taunton_JHR.csv"
f = open(filename, "w") #
headers = "Name, Email, Address\n"
f.write(headers)
for client_url in clients_list:
# call the function to scrape the individual park data
client_url = "http://www.tauntondevelopment.org/msip/" client_url
try:
uClient = uReq(client_url)
except:
print("Error: Unable to open url")
continue # continue to the next client_url in the list
client_name, client_email, client_address = scrapeIndPark(uClient)
f.write(client_name "," client_email "," client_address "\n")
f.close()
uj5u.com熱心網友回復:
您是否嘗試查看下載的 html?
<html>
<head>
<title>
John Hancock Road
</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
</head>
<frameset bordercolor="#E0E0E0" cols="25%,591*">
<frame name="index" src="JHRleft.htm" target="content"/>
<frame name="content" src="JHRright.htm"/>
</frameset>
<noframes>
<body bgcolor="#FFFFFF">
</body>
</noframes>
<frameset>
</frameset>
</html>
請注意(至少在我的情況下)它是空的!這是因為頁面是用框架構建的。要訪問框架,您需要轉到頁面,運行網路檢查器,轉到網路選項卡并查看 url 發送后一個請求(用資料填充框架)。在這種情況下,您搜索的網址可能是http://www.tauntondevelopment.org//msip/JHRleft.htm
uj5u.com熱心網友回復:
在您的代碼中,您試圖從 li 元素本身獲取 href 屬性。實際上 li 元素有一個嵌套的 p 和一個嵌套的 b,里面有一個嵌套,你需要得到那個嵌套的 a。
這是一個建議:
clients_list = []
for link in park_soup.findAll('li'):
href_attr = link.findAll('p')[0].findAll('b')[0].findAll('a').get('href')
clients_list.append(href_attr)
另一個想法是直接使用所有 a 標簽:
clients_list = []
for link in park_soup.findAll('a'):
href_attr = link.get('href')
clients_list.append(href_attr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/382731.html
上一篇:特定元素的網頁抓取選擇器
