我必須像這樣從不同的網路資料表中提取帶有網站網址的部分。
問題是“vermell_nobullet”類的 href 比我需要它重復至少兩次。
如何使用網站的href提取特定類“vermell_nobullet”。
我的代碼
from bs4 import BeautifulSoup
import lxml
import requests
def parse_url(url):
response = requests.get(url)
content = response.content
parsed_response = BeautifulSoup(content, "lxml") # Variable que filtre pel contigut lxml
return parsed_response
depPres = "http://sac.gencat.cat/sacgencat/AppJava/organisme_fitxa.jsp?codi=6"
print(depPres)
soup = parse_url(depPres)
referClass = soup.find_all("a", {"class":"vermell_nobullet"})
referClass
我有的輸出:
[<a class="vermell_nobullet" href="https://ovt.gencat.cat/gsitfc/AppJava/generic/conqxsGeneric.do?webFormId=691">
Bústia electrònica
</a>,
<a class="vermell_nobullet" href="http://presidencia.gencat.cat">http://presidencia.gencat.cat</a>]
我想要的輸出:
http://presidencia.gencat.cat
uj5u.com熱心網友回復:
你可以把條件像 if textand hrefis same from atag 你可以拿特定的 tag
referClass = soup.find_all("a", {"class":"vermell_nobullet"})
for refer in referClass:
if refer.text==refer['href']:
print(refer['href'])
另一種方法找到最后一個div元素,也找到最后一個href使用find_all方法
soup.find_all("div",class_="blockAdresa")[-1].find_all("a")[-1]['href']
輸出:
'http://presidencia.gencat.cat'
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/392386.html
