错误 'NoneType' object has no attribute 'text'
时间: 2023-10-07 11:14:34 浏览: 42
这个错误通常表示没有找到你正在寻找的元素,因此无法使用`text`属性获取其文本内容。为了避免出现这个问题,您可以在使用`select()`或`select_one()`查找元素之前,先检查该元素是否存在。以下是修改后的代码:
```python
import requests
from bs4 import BeautifulSoup
import os
# 创建一个目录用于存储图片
if not os.path.exists('./images'):
os.mkdir('./images')
# 爬取网页的基本信息
url = 'https://www.ppomppu.co.kr/zboard/zboard.php?id=freeboard&hotlist_flag=999'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
articles = soup.select('tr[class^="list"]')
# 遍历每篇文章
for article in articles:
# 获取文章的标题和链接
title_elem = article.select_one('font[class^="list_title"]')
if title_elem is None:
continue
title = title_elem.text.strip()
link_elem = article.select_one('a')
if link_elem is None:
continue
link = 'https://www.ppomppu.co.kr/zboard/' + link_elem['href']
# 获取文章的内容
response = requests.get(link, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
content_elem = soup.select_one('td[class^="view_content"]')
if content_elem is None:
continue
content = content_elem.text.strip()
# 获取文章中的图片
images = content_elem.select('img')
for img in images:
img_url = 'https://www.ppomppu.co.kr' + img['src']
img_name = img['alt'] if img.has_attr('alt') else img['src'].split('/')[-1]
img_path = './images/{}'.format(img_name)
# 下载图片
with open(img_path, 'wb') as f:
f.write(requests.get(img_url).content)
# 替换文章中的图片链接
content = content.replace(img['src'], './images/{}'.format(img_name))
# 打印文章的标题和内容
print(title)
print(content)
```
该程序对每个元素使用了`if`语句进行了检查,确保它们不是`None`对象。如果元素不存在,则跳过该文章,继续遍历其他文章。这样可以避免出现`'NoneType' object has no attribute 'text'`的错误。
您可以根据需要对该程序进行修改,例如修改请求地址、添加请求参数等。