import requests from bs4 import BeautifulSoup codes = ['600887', '002027'] # 伊利股份的股票代码为600887,分众传媒的股票代码为002027 for code in codes: url = f'http://www.sse.com.cn/assortment/stock/list/info/quote/index.shtml?COMPANY_CODE={code}' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') name = soup.find('div', class_='company_info').find('h2').text price = soup.find('span', class_='last').text print(f'{name} 的股价为 {price}') 执行以上代码报一下错误 File "D:\xbro\Blili\kk2.py", line 12, in <module> name = soup.find('div', class_='company_info').find('h2').text AttributeError: 'NoneType' object has no attribute 'find' 根据报错修改代码
时间: 2023-08-15 13:07:34 浏览: 111
import sys import os import urllib from bs4 import BeautifulSoup
根据错误提示,可能是在 `soup.find('div', class_='company_info')` 这一行代码中找不到指定的 `div` 元素,因此返回了 `NoneType` 类型的对象,而该对象没有 `find` 方法,导致了错误。
可以加上判断语句,如果找不到指定的元素,就跳过该次循环,继续执行下一次循环:
```python
import requests
from bs4 import BeautifulSoup
codes = ['600887', '002027']
for code in codes:
url = f'http://www.sse.com.cn/assortment/stock/list/info/quote/index.shtml?COMPANY_CODE={code}'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
name_elem = soup.find('div', class_='company_info').find('h2')
if not name_elem:
continue
name = name_elem.text
price_elem = soup.find('span', class_='last')
if not price_elem:
continue
price = price_elem.text
print(f'{name} 的股价为 {price}')
```
这样就可以避免找不到指定元素时导致的错误了。
阅读全文