1. 程式人生 > >python獲取頁面所有a標籤下href的值

python獲取頁面所有a標籤下href的值

參考下面的連結中的內容:

# -*- coding:utf-8 -*-
#python 2.7
#http://tieba.baidu.com/p/2460150866
#標籤操作


from bs4 import BeautifulSoup
import urllib.request
import re


#如果是網址,可以用這個辦法來讀取網頁
#html_doc = "http://tieba.baidu.com/p/2460150866"
#req = urllib.request.Request(html_doc)  
#webpage = urllib.request.urlopen(req)  
#html = webpage.read()



html="""
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="xiaodeng"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
<a href="http://example.com/lacie" class="sister" id="xiaodeng">Lacie</a>
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html, 'html.parser')   #文件物件


#查詢a標籤,只會查找出一個a標籤
#print(soup.a)#<a class="sister" href="http://example.com/elsie" id="xiaodeng"><!-- Elsie --></a>

for k in soup.find_all('a'):
    print(k)
    print(k['class'])#查a標籤的class屬性
    print(k['id'])#查a標籤的id值
    print(k['href'])#查a標籤的href值
    print(k.string)#查a標籤的string

    如果,標籤<a>中含有其他標籤,比如<em>..</em>,此時要提取<a>中的資料,需要用k.get_text()

soup = BeautifulSoup(html, 'html.parser')   #文件物件 #查詢a標籤,只會查找出一個a標籤

for k in soup.find_all('a'):     print(k)     print(k['class'])#查a標籤的class屬性     print(k['id'])#查a標籤的id值     print(k['href'])#查a標籤的href值     print(k.string)#查a標籤的string

    如果,標籤<a>中含有其他標籤,比如<em>..</em>,此時要提取<a>中的資料,需要用k.get_text()

    通常我們使用下面這種模式也是能夠處理的,下面的方法使用了get()。

 html = urlopen(url)
 soup = BeautifulSoup(html, 'html.parser')
 t1 = soup.find_all('a')
 print t1
 href_list = []
 for t2 in t1:
    t3 = t2.get('href')
    href_list.append(t3)