鱼C论坛

 找回密码
 立即注册
查看: 836|回复: 1

有大神帮忙解决一下吗

[复制链接]
发表于 2023-5-31 14:58:28 | 显示全部楼层 |阅读模式
6鱼币
runfile('D:/dui.py', wdir='D:')
Traceback (most recent call last):

  File "D:\dui.py", line 88, in <module>
    main()

  File "D:\dui.py", line 51, in main
    result_count = get_result_count(query)

  File "D:\dui.py", line 20, in get_result_count
    result_stats = soup.find(id='result-stats').text

AttributeError: 'NoneType' object has no attribute 'text'




import requests
import pandas as pd
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt

# 获取百度搜索结果
def get_search_result(query):
    url = f'https://www.baidu.com/s?wd={query}'
    headers = {
        'Accept-Encoding': 'gzip, deflate, br',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    return response.text
# 解析搜索结果页面,获取结果数
def get_result_count(query):
    html = get_search_result(query)
    soup = BeautifulSoup(html, 'html.parser')
    result_stats = soup.find(id='result-stats').text
    result_count = int(''.join(filter(str.isdigit, result_stats)))
    return result_count
# 解析搜索结果页面,获取百度百科信息
def get_baike_info(query):
    url = f'https://baike.baidu.com/item/{query}'
    headers = {
        'Accept-Encoding': 'gzip, deflate, br',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    response.encoding = response.apparent_encoding
    soup = BeautifulSoup(response.text, 'html.parser')
   
    try:
        info_tables = soup.find_all('table', class_='basicInfo')
        headers = [header.text.strip() for header in info_tables[0].find_all('dt')]
        values = []
        for value in info_tables[0].find_all('dd'):
            value_text = value.text.strip()
            value_text = value_text.replace('\n', '')
            value_text = value_text.replace('\xa0', '')
            values.append(value_text)
            
        info_dict = dict(zip(headers, values))
        return info_dict
   
    except:
        return None
def main():
    query = '农业 湿度温度自然灾害次数 农业产量'
    result_count = get_result_count(query)
    print(f'总共找到{result_count}个相关搜索结果\n')
    info_list = []
   
    for page in range(0, 10, 10):
        url = f'https://www.baidu.com/s?wd={query}&pn={page}'
        html = get_search_result(url)
        soup = BeautifulSoup(html, 'html.parser')
        results = soup.find_all('div', class_='result')
        for result in results:
            title = result.find('h3').text
            link = result.find('a')['href']
            baike_info = get_baike_info(title)
            if baike_info is not None:
                info = {
                    '标题': title,
                    '链接': link,
                    '温度': baike_info.get('适宜温度'),
                    '湿度': baike_info.get('湿度'),
                    '自然灾害次数': baike_info.get('自然灾害频率'),
                    '农业产量': baike_info.get('农业产量')
                }
                info_list.append(info)
    # 将获取的数据转换为dataframe
    df = pd.DataFrame(info_list)
    # 将各列的数据类型修改为float
    df['温度'] = df['温度'].astype('float')
    df['湿度'] = df['湿度'].astype('float')
    df['自然灾害次数'] = df['自然灾害次数'].astype('float')
    df['农业产量'] = df['农业产量'].astype('float')
    # 绘制散点图
    plt.scatter(df['自然灾害次数'], df['农业产量'])
    plt.xlabel('自然灾害次数')
    plt.ylabel('农业产量')
    # 显示图表
    plt.show()
if __name__== '__main__':
    main()



     



想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-5-31 16:23:44 | 显示全部楼层
看起来你的代码在尝试从百度搜索结果页面获取搜索结果数时遇到了问题。这个问题发生在函数 `get_result_count` 中,其尝试找到 id 为 'result-stats' 的元素并提取其文本。报错提示 'NoneType' object has no attribute 'text',说明 `soup.find(id='result-stats')` 没有找到对应的元素,返回了 None。

有几个可能的原因:

1. 百度页面的结构已经改变,导致id为 'result-stats' 的元素不存在。如果是这种情况,你需要检查当前百度搜索页面的HTML结构,并调整你的代码以适应新的结构。

2. 你可能面临 IP 被百度屏蔽或者访问频率过高等问题,导致百度并没有返回完整的搜索结果页面。如果是这种情况,你需要调整你的抓取策略,比如增加请求间的延时,或者使用代理 IP。

你可以首先访问百度搜索并进行一次手动搜索,检查搜索结果页面的HTML结构是否有所变化。

另外,你的代码中有一部分是尝试从百度百科中获取信息,这可能存在问题,因为并非所有的搜索结果都会在百度百科中有对应的页面,如果直接以标题作为百度百科的查询对象,可能会导致找不到结果或者找到的结果并不是预期的结果。

注意,网络爬虫需要遵守网站的robots.txt规则以及各国的相关法律,且频繁的请求可能导致IP被封,因此在设计爬虫时要尽可能地考虑这些因素。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 10:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表