我嘗試在 Google 中搜索所有以“gencat.cat”結尾的網站。
我的代碼:
import requests, lxml
from bs4 import BeautifulSoup
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582"
}
params = {'q': 'gencat.cat'}
html = requests.get('https://www.google.com/search', headers=headers, params=params).text
soup = BeautifulSoup(html, 'lxml')
# containver with all needed data
for result in soup.select('.tF2Cxc'):
link = result.a['href'] # or ('.yuRUbf a')['href']
print(link)
我有的輸出:
問題是只搜索了幾個網站,并且需要一些沒有“gencat.cat”的網址或重復來自同一網站的頁面:
https://web.gencat.cat/ca/inici
https://web.gencat.cat/es/inici/
https://web.gencat.cat/ca/tramits
https://web.gencat.cat/en/inici/index.html
https://govern.cat/
https://govern.cat/salapremsa/
http://www.gencat.es/
http://www.regencos.cat/promocio-variable/preguntes-mes-frequents-sobre-el-coronavirus/
https://tauler.seu.cat/inici.do?idens=1
我想要的輸出:
https://web.gencat.cat
http://agricultura.gencat.cat
http://cultura.gencat.cat
https://dretssocials.gencat.cat
http://economia.gencat.cat
uj5u.com熱心網友回復:
如果您想要頂級域,您可以拆分link變數中所有“/”實體上的鏈接。
for result in soup.select('.tF2Cxc'):
link = result.a['href'] # or ('.yuRUbf a')['href']
print(link)
string_splt = link.split("/")
TLD = f"https://{string_splt[2]}"
print(TLD)
我相信有更好的方法可以將它們重新組合在一起,但這似乎有效。您還需要處理重復項。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/389817.html
上一篇:網頁抓取專案串列
下一篇:selenium.common.exceptions.WebDriverException:訊息:“WebScraping”可執行檔案可能有錯誤的權限
