3 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
取決于你想用塊做什么,如果只有在href之后使用并使用后代組合select器指定具有子元素的父類和屬性href
import requests
from bs4 import BeautifulSoup
ticker='FAST'
url = "https://www.google.com/search?q=nasdaq+%s+earnings+reaction+history&tbs=qdr:m"%(ticker)
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
cache = [searchs['href'] for searchs in soup.select('div.kCrYT [href]')]
print(''.join(cache))

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
使用下面的代碼從TypeError.
try:
cache.append(searchs.find('a')['href'])
except TypeError:
continue

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
不要試圖在一行中放這么多:
...
for searchs in soup.find_all('div'):
tag = searchs.find('a')
#print(searchs)
if not tag:
continue
try:
h = tag['href']
except KeyError as e:
continue
print(h)
添加回答
舉報(bào)