鱼C论坛

 找回密码
 立即注册

求一个pyhton的爬虫!

[复制链接]
 楼主| 发表于 2023-12-18 16:58:51 | 显示全部楼层
FishC 发表于 2023-12-18 16:54
这个错误是因为你提供的文本中没有足够的词语生成词云图。可能是因为在解析新闻文本时出现了问题。请确认 ...

请重新审视代码,目前的代码运行失败
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-12-18 16:59:08 | 显示全部楼层
豪在这学python 发表于 2023-12-18 16:58
请重新审视代码,目前的代码运行失败

非常抱歉,之前提供的代码有一处错误。在生成词云图之前,我们需要先对文本进行处理,确保至少有一个词语才能生成词云图。以下是修正后的代码:
  1. import requests
  2. import jieba
  3. from wordcloud import WordCloud
  4. def get_text_from_weibo(url):
  5.     # 发送GET请求获取网页内容
  6.     response = requests.get(url)
  7.     # 获取网页内容
  8.     html = response.text
  9.     return html
  10. def generate_wordcloud(text):
  11.     # 分词
  12.     seg_list = jieba.cut(text)
  13.     words = " ".join(seg_list)
  14.    
  15.     if len(words) > 0:  # 如果分词后的文本不为空
  16.         # 创建词云对象
  17.         wc = WordCloud(background_color="white", width=800, height=400, max_words=200, font_path='simhei.ttf')
  18.         # 生成词云图
  19.         wc.generate(words)
  20.         # 保存词云图
  21.         wc.to_file("wordcloud.png")
  22.     else:
  23.         print("文本为空,无法生成词云图!")
  24. if __name__ == '__main__':
  25.     # 新浪微博页面URL
  26.     url = "https://weibo.com/"
  27.     # 获取微博内容
  28.     weibo_text = get_text_from_weibo(url)
  29.     # 生成词云图
  30.     generate_wordcloud(weibo_text)
复制代码

这次在生成词云图之前添加了判断条件,当分词后的文本长度大于0时,才生成词云图。如果文本为空,将会打印出一条错误提示信息。请注意要确保`simhei.ttf`字体文件存在,并且与代码中的路径保持一致。希望这次能够成功生成词云图!如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-12-18 17:01:29 | 显示全部楼层
FishC 发表于 2023-12-18 16:59
非常抱歉,之前提供的代码有一处错误。在生成词云图之前,我们需要先对文本进行处理,确保至少有一个词语 ...

我需要获取的是新闻头条文本
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-12-18 17:03:21 | 显示全部楼层
豪在这学python 发表于 2023-12-18 17:01
我需要获取的是新闻头条文本

非常抱歉,之前的代码和注释有误。下面是一个可以获取新浪新闻头条文本的爬虫示例代码:
  1. import requests
  2. from bs4 import BeautifulSoup
  3. def get_headlines():
  4.     # 新浪新闻首页URL
  5.     url = "https://news.sina.com.cn/"
  6.    
  7.     try:
  8.         # 发送GET请求获取网页内容
  9.         response = requests.get(url)
  10.         # 设置编码方式
  11.         response.encoding = 'utf-8'
  12.         # 获取网页内容
  13.         html = response.text
  14.         
  15.         # 使用BeautifulSoup解析网页内容
  16.         soup = BeautifulSoup(html, 'html.parser')
  17.         
  18.         # 获取新闻头条部分的HTML元素
  19.         headlines_div = soup.select('.blk_02')[0]
  20.         
  21.         # 获取每条新闻的标题
  22.         headlines = []
  23.         for item in headlines_div.select('a'):
  24.             title = item.text.strip()
  25.             if title:
  26.                 headlines.append(title)
  27.         return headlines
  28.         
  29.     except requests.exceptions.RequestException as e:
  30.         print("网络请求出错:", e)
  31.     except Exception as e:
  32.         print("解析页面出错:", e)
  33. if __name__ == '__main__':
  34.     headlines = get_headlines()
  35.     for i, title in enumerate(headlines, 1):
  36.         print(f"新闻{i}:{title}")
复制代码

上述代码使用了`requests`和`BeautifulSoup`库来发送网络请求并解析网页内容。其中`get_headlines()`函数通过选择器从新浪新闻首页中提取新闻头条部分的HTML元素,并遍历每个新闻链接的文本,将其存储在一个列表中。

你可以在`if __name__ == '__main__':`部分使用返回的新闻标题列表做任何进一步处理,比如生成词云图等。希望这次能够满足你的需求!如果还有其他问题,请随时提问。为了让爬虫获得的数据更可靠,请确保遵守相关网站的爬取规则,并在代码中添加适当的异常处理。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-12-18 17:06:47 | 显示全部楼层
FishC 发表于 2023-12-18 17:03
非常抱歉,之前的代码和注释有误。下面是一个可以获取新浪新闻头条文本的爬虫示例代码:

我还需要新闻头条的具体内容
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-12-18 17:07:46 | 显示全部楼层
豪在这学python 发表于 2023-12-18 17:06
我还需要新闻头条的具体内容

非常抱歉之前的回答有误。要获取新闻头条的具体内容,可以在获取新闻标题后,再通过爬取对应链接的详情页面来获取具体内容。

下面是修改后的示例代码:
  1. import requests
  2. from bs4 import BeautifulSoup
  3. def get_headlines():
  4.     # 新浪新闻首页URL
  5.     url = "https://news.sina.com.cn/"
  6.     try:
  7.         # 发送GET请求获取网页内容
  8.         response = requests.get(url)
  9.         # 设置编码方式
  10.         response.encoding = 'utf-8'
  11.         # 获取网页内容
  12.         html = response.text
  13.         # 使用BeautifulSoup解析网页内容
  14.         soup = BeautifulSoup(html, 'html.parser')
  15.         # 获取新闻头条部分的HTML元素
  16.         headlines_div = soup.select('.blk_02')
  17.         headlines = []
  18.         for item in headlines_div.select('a'):
  19.             title = item.text.strip()
  20.             if title:
  21.                 # 获取新闻详情页面URL
  22.                 news_url = item['href']
  23.                 # 获取新闻详情页面的内容
  24.                 news_content = get_news_content(news_url)
  25.                 # 将标题和内容存储为字典
  26.                 news = {'title': title, 'content': news_content}
  27.                 headlines.append(news)
  28.         return headlines
  29.     except requests.exceptions.RequestException as e:
  30.         print("网络请求出错:", e)
  31.     except Exception as e:
  32.         print("解析页面出错:", e)
  33. def get_news_content(url):
  34.     try:
  35.         # 发送GET请求获取新闻详情页面内容
  36.         response = requests.get(url)
  37.         response.encoding = 'utf-8'
  38.         html = response.text
  39.         # 使用BeautifulSoup解析新闻详情页面内容
  40.         soup = BeautifulSoup(html, 'html.parser')
  41.         # 根据实际情况,使用适当的选择器获取新闻内容
  42.         content_div = soup.select('.article')[0]
  43.         content = content_div.text.strip()
  44.         return content
  45.     except requests.exceptions.RequestException as e:
  46.         print("网络请求出错:", e)
  47.     except Exception as e:
  48.         print("解析页面出错:", e)
  49. if __name__ == '__main__':
  50.     headlines = get_headlines()
  51.     for i, news in enumerate(headlines, 1):
  52.         print(f"新闻{i}:{news['title']}")
  53.         print(f"内容:{news['content']}")
  54.         print()
复制代码

在上述代码中,我们新增了`get_news_content()`函数用于获取新闻详情页面的内容。通过调用`get_news_content()`函数,并传入新闻链接,我们可以获取每条新闻的具体内容。然后,将标题和内容存储为字典,并将所有新闻存储在一个列表中。最后,按照需要进行打印或其他操作。

希望这次回答能满足你的需求!如果还有其他问题,请随时提问。同样,为了让爬虫获得的数据更可靠,请确保遵守相关网站的爬取规则,并在代码中添加适当的异常处理。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-12-18 17:09:57 | 显示全部楼层
FishC 发表于 2023-12-18 17:07
非常抱歉之前的回答有误。要获取新闻头条的具体内容,可以在获取新闻标题后,再通过爬取对应链接的详情页 ...

TypeError: 'NoneType' object is not iterable
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-12-18 17:10:28 | 显示全部楼层
豪在这学python 发表于 2023-12-18 17:09
TypeError: 'NoneType' object is not iterable

这个错误通常是因为在遍历`headlines_div`时,没有找到符合条件的元素,导致`headlines_div`被赋值为`None`。为了避免这个错误,可以在循环之前加入判断条件来确保获取到了正确的新闻头条部分的HTML元素。修改后的代码如下:import requestsfrom bs4 import BeautifulSoupdef get_headlines():    # 新浪新闻首页URL    url = "https://news.sina.com.cn/"    try:        # 发送GET请求获取网页内容        response = requests.get(url)        # 设置编码方式        response.encoding = 'utf-8'        # 获取网页内容        html = response.text        # 使用BeautifulSoup解析网页内容        soup = BeautifulSoup(html, 'html.parser')        # 获取新闻头条部分的HTML元素        headlines_div = soup.select('.blk_02')        headlines = []        if headlines_div:            for item in headlines_div[0].select('a'):                title = item.text.strip()                if title:                    # 获取新闻详情页面URL                    news_url = item['href']                    # 获取新闻详情页面的内容                    news_content = get_news_content(news_url)                    # 将标题和内容存储为字典                    news = {'title': title, 'content': news_content}                    headlines.append(news)        return headlines    except requests.exceptions.RequestException as e:        print("网络请求出错:", e)    except Exception as e:        print("解析页面出错:", e)def get_news_content(url):    try:        # 发送GET请求获取新闻详情页面内容        response = requests.get(url)        response.encoding = 'utf-8'        html = response.text        # 使用BeautifulSoup解析新闻详情页面内容        soup = BeautifulSoup(html, 'html.parser')        # 根据实际情况,使用适当的选择器获取新闻内容        content_div = soup.select('.article')[0]        content = content_div.text.strip()        return content    except requests.exceptions.RequestException as e:        print("网络请求出错:", e)    except Exception as e:        print("解析页面出错:", e)if __name__ == '__main__':    headlines = get_headlines()    for i, news in enumerate(headlines, 1):        print(f"新闻{i}:{news['title']}")        print(f"内容:{news['content']}")        print()现在,我们在检查`headlines_div`是否存在的同时,也通过索引`[0]`确保只选择第一个符合条件的元素来获取新闻标题。此外,在打印新闻标题和内容时,请使用字典中相应的键来访问对应的值。希望这次修正能解决报错问题!如果还有任何疑问,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-12-18 17:11:36 | 显示全部楼层
FishC 发表于 2023-12-18 17:10
这个错误通常是因为在遍历`headlines_div`时,没有找到符合条件的元素,导致`headlines_div`被赋值为`Non ...

整理代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-12-18 17:12:20 | 显示全部楼层

当然!下面是经过整理的代码示例:
  1. import requests
  2. from bs4 import BeautifulSoup
  3. def get_headlines():
  4.     # 新浪新闻首页URL
  5.     url = "https://news.sina.com.cn/"
  6.     try:
  7.         # 发送GET请求获取网页内容
  8.         response = requests.get(url)
  9.         # 设置编码方式
  10.         response.encoding = 'utf-8'
  11.         # 获取网页内容
  12.         html = response.text
  13.         # 使用BeautifulSoup解析网页内容
  14.         soup = BeautifulSoup(html, 'html.parser')
  15.         # 获取新闻头条部分的HTML元素
  16.         headlines_div = soup.select('.blk_02')
  17.         headlines = []
  18.         if headlines_div:
  19.             for item in headlines_div[0].select('a'):
  20.                 title = item.text.strip()
  21.                 if title:
  22.                     # 获取新闻详情页面URL
  23.                     news_url = item['href']
  24.                     # 获取新闻详情页面的内容
  25.                     news_content = get_news_content(news_url)
  26.                     # 将标题和内容存储为字典
  27.                     news = {'title': title, 'content': news_content}
  28.                     headlines.append(news)
  29.         return headlines
  30.     except requests.exceptions.RequestException as e:
  31.         print("网络请求出错:", e)
  32.     except Exception as e:
  33.         print("解析页面出错:", e)
  34. def get_news_content(url):
  35.     try:
  36.         # 发送GET请求获取新闻详情页面内容
  37.         response = requests.get(url)
  38.         response.encoding = 'utf-8'
  39.         html = response.text
  40.         # 使用BeautifulSoup解析新闻详情页面内容
  41.         soup = BeautifulSoup(html, 'html.parser')
  42.         # 根据实际情况,使用适当的选择器获取新闻内容
  43.         content_div = soup.select('.article')
  44.         if content_div:
  45.             content = content_div[0].text.strip()
  46.             return content
  47.         else:
  48.             return ""
  49.     except requests.exceptions.RequestException as e:
  50.         print("网络请求出错:", e)
  51.     except Exception as e:
  52.         print("解析页面出错:", e)
  53. if __name__ == '__main__':
  54.     headlines = get_headlines()
  55.     for i, news in enumerate(headlines, 1):
  56.         print(f"新闻{i}:{news['title']}")
  57.         print(f"内容:{news['content']}")
  58.         print()
复制代码

在这个整理后的代码中,主要进行了以下优化:

1. 对于`headlines_div`和`content_div`的判断,使用了索引`[0]`来确保只取第一个符合条件的元素。
2. 在获取新闻详情页面URL时,通过`item['href']`来直接获取URL属性值。
3. 在获取新闻内容时,加入了对`content_div`是否存在的判断,并返回空字符串作为默认值。
4. 打印新闻标题和内容时,使用了字典中相应的键来访问对应的值。

希望这次整理的代码能更好地解决问题!如果还有其他疑问,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-6-3 04:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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