0

私はこの簡単なコードを持っています:

#usr/bin/python

from bs4 import BeautifulSoup
import requests
import tldextract

def scrape(url):
    main_domain = tldextract.extract(url)
    r = requests.get(url)
    data = r.text
    soup = BeautifulSoup(data)
    list = []
    for href in soup.find_all('a'):
    link_domain = tldextract.extract(href.get('href'))
    print link_domain
    print

取得エラー:

Traceback (most recent call last):
File "cloud.py", line 20, in <module>
scrape("--- url here -- ")
File "cloud.py", line 14, in scrape
link_domain = tldextract.extract(href.get('href'))
File "/usr/lib/python2.6/site-packages/tldextract/tldextract.py", line 196, in extract 
return TLD_EXTRACTOR(url)
File "/usr/lib/python2.6/site-packages/tldextract/tldextract.py", line 127, in __call__
netloc = SCHEME_RE.sub("", url) \

TypeError: expected string or buffer

どうすれば修正できますか。

4

1 に答える 1

0

一部のaタグには属性がないため、 が返されます。href.get('href')None

使用する:

link_domain = tldextract.extract(href.get('href', ''))

その場合は空の文字列を返すか、最初に属性をテストします。

href = href.get('href')
if not href:
    continue

link_domain = tldextract.extract(href)
于 2013-07-19T12:40:37.160 に答える