2017-05-11 137 views
1

我寫了一個小腳本,用python從網頁中讀取所有的hrefs。 但它有一個問題。例如,它不會讀取href="pages.php?ef=fa&page=n_fullstory.php&NewsIDn=1648"網絡抓取:全部href

代碼:

import urllib 
import re 

urls = ["http://something.com"] 

regex='href=\"(.+?)\"' 
pattern = re.compile(regex) 

htmlfile = urllib.urlopen(urls[0]) 
htmltext = htmlfile.read() 
hrefs = re.findall(pattern,htmltext) 
print hrefs 

任何人可以幫助我嗎?謝謝。

+0

一般建議:不要用正則表達式解析HTML。雖然你可以實施你的特定案例,但如果你需要更多的東西,它可能會非常快速地變得非常混亂。改爲使用正確的解析庫。查看[BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)或['lxml.html'](http://lxml.de/lxmlhtml.html)。或者甚至可能是[Scrapy](https://scrapy.org/)。 – drdaeman

回答

1

使用BEautifulSoup和請求靜態網站。它是一個偉大的網頁報廢模塊,使用代碼,很容易就可以獲得href標籤內的值。希望它有幫助

import requests 
from bs4 import BeautifulSoup 

url = 'whatever url you want to parse' 

result = requests.get(url) 

soup = BeautifulSoup(result.content,'html.parser') 

for a in soup.find_all('a',href=True): 
    print "Found the URL:", a['href']