python開啟網頁中的鏈結需要用到的模組和方法

2021-09-23 20:54:09 字數 1339 閱讀 2791

# 呼叫chrome瀏覽器並後台執行

option=webdriver.chromeoptions()

option.add_argument('headless')

driver = webdriver.chrome(options=option)

# driver = webdriver.chrome()

driver.get("") # 要測試的頁面

urls = driver.find_elements_by_xpath("//a") # 匹配出所有a元素裡的鏈結

success_count = 0

fail_count = 0

for url in urls:

real_url = url.get_attribute('href')

if real_url == 'none': # 很多的a元素沒有鏈結,所以是none

continue

try:

response = urllib.request.urlopen(real_url) # 可以通過urllib測試url位址是否能開啟

time.sleep(1)

except urlerror as reason:

fail_count += 1

print('問題鏈結%d顯示的是:'%fail_count, real_url, '對應的文字是:' + url.get_attribute("text")) # 把測試不通過的url顯示出來

else:

success_count += 1

print('可用鏈結%d是:'%success_count, real_url) # 測試通過的url展示出來

driver.close()

網頁中鏈結的分類

按照鏈結路徑的不同,網頁中的超連結一般分為三種型別 1 內部鏈結 單擊該超連結連線到同一 的另外乙個頁面。2 錨點鏈結 單擊該超連結連線到同一頁面的某乙個位置 3 外部鏈結 單擊該超連結連線到其他 上的某乙個頁面 按照使用物件的不同,網頁中的鏈結可以分為 1 文字超連結 建立在文字上的超連結 2 影...

提取網頁中的超連結

using system using system.xml using system.text using system.net using system.io using system.collections using system.text.regularexpressions console...

提取網頁中的超連結

using system using system.xml using system.text using system.net using system.io using system.collections using system.text.regularexpressions console...