[英]Unique list of links from HTML using Python
因此,我有一個腳本可以從網站中提取所有鏈接,我認為轉換為列表可以確保我僅返回唯一鏈接,但是輸出中仍然有重復項(例如,www.commerce.gov) /”和“ www.commerce.gov”),則代碼未選擇尾隨字符。 下面是我的代碼。 任何幫助表示贊賞。 謝謝。
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re
import csv
req = Request("https://www.census.gov/programs-surveys/popest.html")
html_page = urlopen(req)
soup = BeautifulSoup(html_page, "lxml")
prettyhtml = soup.prettify()
Html_file = open("U:\python_intro\popest_html.txt","w")
Html_file.write(prettyhtml)
Html_file.close()
links = []
for link in soup.findAll('a', attrs={'href': re.compile(r'^(?:http|ftp)s?://')}):
links.append(link.get('href'))
links = set(links)
myfile = "U:\python_stuff\links.csv"
with open(myfile, "w") as output:
writer = csv.writer(output, lineterminator='\n')
for a in links:
writer.writerow([a])
您的意思是“轉換為一組”而不是列表。
您可以刪除任何可能的結尾'/'
:
links.append(link.get('href').rstrip('/'))
甚至更好,從頭開始構建一個集合:
links = set() for link in soup.findAll('a', attrs={'href': re.compile(r'^(?:http|ftp)s?://')}): links.add(link.get('href').rstrip('/'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.