【发布时间】:2022-01-03 23:39:09
【问题描述】:
所以我制作了一个网络爬虫,一切似乎都运行良好,但是,没有返回任何值?假设网址有问题,但我似乎看不到任何东西。
import pandas as pd
import datetime
import requests
from requests.exceptions import ConnectionError
from bs4 import BeautifulSoup
def web_content_div(web_content, class_path):
web_content_div = web_content.find_all('div', {'class': class_path})
try:
spans = web_content_div[0].find_all('span')
texts = [span.get_text() for span in spans]
except IndexError:
texts = []
return texts
def real_time_price(stock_code):
url= 'https://uk.finance.yahoo.com/quote/' + stock_code + '?p=' + stock_code + '&.tsrc=fin-tre-srch'
try:
r = requests.get(url)
web_content = BeautifulSoup(r.text, 'lxml')
texts = web_content_div(web_content, 'My(6px) Pos(r) smartphone_Mt(6px) W(100%)')
if texts != []:
price, change = texts[0], texts[1]
else:
price, change = [], []
except ConnectionError:
price, change = [], []
return price, change
Stock = ['BRK-B']
print(real_time_price('BRK-B'))
【问题讨论】:
-
你调试了吗?什么(哪一行)返回“无值”(然后返回什么)?
-
请在提问前搜索 SO - 这一定是最常见的问题之一,几乎所有情况下的答案都是“用户代理”、“cookies”或“使用
selenium启用 JavaScript” - 除非您已检查所有三个,否则很明显您根本没有真正努力寻找答案。
标签: python