python來獲取網頁中的所有鏈接


注意:使用前要裝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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM