注意:使用前要裝selenium第三方的庫才可以使用
版本:python3
from bs4 import BeautifulSoup from urllib import request # 要請求的網絡地址 url = 'https://www.hao123.com/' # 請求網絡地址得到html網頁代碼 html = request.urlopen(url) # 整理代碼 soup = BeautifulSoup(html, 'html.parser') # 找出所有的 a 標簽, 因為所有的鏈接都在 a 標簽內 data = soup.find_all('a') # 打開文件對象做持久化操作 file = open('D:/link.txt', mode='w', encoding='utf-8') # 遍歷所有的 a 標簽, 獲取它們的 href 屬性的值和它們的 text for item in data: if item.string is not None and item['href'] != 'javascript:;' and item['href'] != '#': print(item.string, item.get('href')) file.write(str.__add__(item.string, ' ')) file.write(str.__add__(item['href'], '\n')) file.close()