鱼C论坛

 找回密码
 立即注册
查看: 1217|回复: 8

代码错误在哪

[复制链接]
发表于 2023-5-31 13:05:51 | 显示全部楼层 |阅读模式
6鱼币

QQ图片20230531130255.png

爬虫.zip

12.23 KB, 下载次数: 2

爬虫.zip

12.23 KB, 下载次数: 1

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

使用道具 举报

发表于 2023-5-31 13:34:20 | 显示全部楼层
你的代码和报错信息就不能直接粘贴出来吗?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-5-31 14:03:01 | 显示全部楼层
isdkz 发表于 2023-5-31 13:34
你的代码和报错信息就不能直接粘贴出来吗?

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 14:04:50 | 显示全部楼层
isdkz 发表于 2023-5-31 13:34
你的代码和报错信息就不能直接粘贴出来吗?

runfile('D:/dui.py', wdir='D:')
Traceback (most recent call last):

  File "D:\dui.py", line 87, in <module>
    if _name_== '_main_':

NameError: name '_name_' is not defined
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-5-31 14:09:05 | 显示全部楼层
tttttt@@@@@@ 发表于 2023-5-31 14:04
runfile('D:/dui.py', wdir='D:')
Traceback (most recent call last):


if __name__== '__main__':

这里是双下划线才对
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2023-5-31 14:14:17 | 显示全部楼层
isdkz 发表于 2023-5-31 14:09
if __name__== '__main__':

这里是双下划线才对

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'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-5-31 15:20:24 | 显示全部楼层
错误:

1. Import应为import,Python关键字应该小写。
2. if _name__== '_main_':中的双下划线应为单下划线,应为if __name__ == '__main__':。
下面是已修正的代码:
  1. import requests
  2. import pandas as pd
  3. from bs4 import BeautifulSoup
  4. import matplotlib.pyplot as plt

  5. # 获取百度搜索结果
  6. def get_search_result(query):
  7.     url = f'https://www.baidu.com/s?wd={query}'
  8.     headers = {
  9.         'Accept-Encoding': 'gzip, deflate, br',
  10.         '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'
  11.     }
  12.     response = requests.get(url, headers=headers)
  13.     response.encoding = response.apparent_encoding
  14.     return response.text

  15. # 解析搜索结果页面,获取结果数
  16. def get_result_count(query):
  17.     html = get_search_result(query)
  18.     soup = BeautifulSoup(html, 'html.parser')
  19.     result_stats = soup.find(id='result-stats').text
  20.     result_count = int(''.join(filter(str.isdigit, result_stats)))
  21.     return result_count

  22. # 解析搜索结果页面,获取百度百科信息
  23. def get_baike_info(query):
  24.     url = f'https://baike.baidu.com/item/{query}'
  25.     headers = {
  26.         'Accept-Encoding': 'gzip, deflate, br',
  27.         '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'
  28.     }
  29.     response = requests.get(url, headers=headers)
  30.     response.encoding = response.apparent_encoding
  31.     soup = BeautifulSoup(response.text, 'html.parser')

  32.     try:
  33.         info_tables = soup.find_all('table', class_='basicInfo')
  34.         headers = [header.text.strip() for header in info_tables[0].find_all('dt')]
  35.         values = []
  36.         for value in info_tables[0].find_all('dd'):
  37.             value_text = value.text.strip()
  38.             value_text = value_text.replace('\n', '')
  39.             value_text = value_text.replace('\xa0', '')
  40.             values.append(value_text)

  41.         info_dict = dict(zip(headers, values))
  42.         return info_dict

  43.     except:
  44.         return None

  45. def main():
  46.     query = '农业 湿度温度自然灾害次数 农业产量'
  47.     result_count = get_result_count(query)
  48.     print(f'总共找到{result_count}个相关搜索结果\n')
  49.     info_list = []

  50.     for page in range(0, 10, 10):
  51.         url = f'https://www.baidu.com/s?wd={query}&pn={page}'
  52.         html = get_search_result(url)
  53.         soup = BeautifulSoup(html, 'html.parser')
  54.         results = soup.find_all('div', class_='result')
  55.         for result in results:
  56.             title = result.find('h3').text
  57.             link = result.find('a')['href']
  58.             baike_info = get_baike_info(title)
  59.             if baike_info is not None:
  60.                 info = {
  61.                     '标题': title,
  62.                     '链接': link,
  63.                     '温度': baike_info.get('适宜温度'),
  64.                     '湿度': baike_info.get('湿度'),
  65.                     '自然灾害次数': baike_info.get('自然灾害频率'),
  66.                     '农业产量': baike_info.get('农业产量')
  67.                 }
  68.                 info_list.append(info)
  69.    
  70.     # 将获取的数据转换为dataframe
  71.     df = pd.DataFrame(info_list)
  72.     # 将各列的数据类型修改为float
  73.     df['温度'] = df['温度'].astype('float')
  74.     df['湿度'] = df['湿度'].astype('float')
  75.     df['自然灾害次数'] = df['自然灾害次数'].astype('float')
  76.     df['农业产量'] = df['农业产量'].astype('float')
  77.    
  78.     # 绘制散点图
  79.     plt.scatter(df['自然灾害次数'], df['农业产量'])
  80.     plt.xlabel('自然灾害次数')
  81.     plt.ylabel('农业产量')
  82.    
  83.     # 显示图表
  84.     plt.show()

  85. if __name__ == '__main__':
  86.     main()
复制代码

这是修正后的代码,现在应该可以运行并绘制散点图。请确保你的环境中已安装必要的库(requests、pandas、beautifulsoup4、matplotlib)。如果没有安装,请使用以下命令安装:
  1. pip install requests pandas beautifulsoup4 matplotlib
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-5-31 16:20:25 | 显示全部楼层
学习了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-5-31 16:23:28 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-27 00:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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