0
我正在構建一個網絡爬蟲,它可以掃描網站以查找推特鏈接。我是新來的美麗的湯,我很難過。我曾嘗試使用正則表達式來解析頁面的整個HTML,但這種方法的效果不及美麗的湯。目前我的代碼抓取一個網站,並試圖解析它的Twitter網址。如何從大多數網站獲取推特鏈接 - Python
當然,我知道這不會總是有效,但現在一切都會返回爲None,並且永遠不會返回Twitter鏈接,但我知道這些網站包含它們。進一步,一旦有5個鏈接我一般也收到錯誤:
AttributeError: 'NoneType' object has no attribute 'group'
我已經特別針對測試。我真的不認爲這應該是這麼難,但考慮到這一點,我認爲我必須在我沒有看到的美麗的臉上出現巨大的根本缺陷。有任何想法嗎?
def twitter_grab(url):
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib2.Request(url, headers=hdr)
response = urllib2.urlopen(req)
soup = BeautifulSoup(response, 'html.parser')
links = soup.find_all('a' or 'li')
for tag in links:
link = tag.get('href', None)
if link is not None:
text = re.search(r'http://www\.twitter\.com/(\w+)', link)
if text is not None:
handle = text.group(0)
print handle
return(handle)
你能否提供一個示例url,以便我們可以看到你想要解析的內容,如果你知道並非每個頁面都有twitter鏈接,則還需要實現異常。 –
你不需要所有的頭文件,只需要'User-Agent'。你不需要'li'標籤。 'get'默認返回'None'。你的正則表達式只抓取HTTP鏈接。除此之外,我沒有看到你的代碼有任何問題。 –
選擇任何有Twitter的隨機公司網站。 「無」正在被用來代替例外,並應予以補償。 @ t.m.adam,'a'不返回列表中的行,它們往往有鏈接。我遇到的一個例子是Newyorklife.com – WolVes