鱼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
请重新审视代码,目前的代码运行失败

非常抱歉,之前提供的代码有一处错误。在生成词云图之前,我们需要先对文本进行处理,确保至少有一个词语才能生成词云图。以下是修正后的代码:
import requestsimport jiebafrom wordcloud import WordClouddef get_text_from_weibo(url):    # 发送GET请求获取网页内容    response = requests.get(url)    # 获取网页内容    html = response.text    return htmldef generate_wordcloud(text):    # 分词    seg_list = jieba.cut(text)    words = " ".join(seg_list)        if len(words) > 0:  # 如果分词后的文本不为空        # 创建词云对象        wc = WordCloud(background_color="white", width=800, height=400, max_words=200, font_path='simhei.ttf')        # 生成词云图        wc.generate(words)        # 保存词云图        wc.to_file("wordcloud.png")    else:        print("文本为空,无法生成词云图!")if __name__ == '__main__':    # 新浪微博页面URL    url = "https://weibo.com/"    # 获取微博内容    weibo_text = get_text_from_weibo(url)    # 生成词云图    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
我需要获取的是新闻头条文本

非常抱歉,之前的代码和注释有误。下面是一个可以获取新浪新闻头条文本的爬虫示例代码:
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')[0]                # 获取每条新闻的标题        headlines = []        for item in headlines_div.select('a'):            title = item.text.strip()            if title:                headlines.append(title)        return headlines            except requests.exceptions.RequestException as e:        print("网络请求出错:", e)    except Exception as e:        print("解析页面出错:", e)if __name__ == '__main__':    headlines = get_headlines()    for i, title in enumerate(headlines, 1):        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
我还需要新闻头条的具体内容

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

下面是修改后的示例代码:
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 = []        for item in headlines_div.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()
在上述代码中,我们新增了`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 | 显示全部楼层

当然!下面是经过整理的代码示例:
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')        if content_div:            content = content_div[0].text.strip()            return content        else:            return ""    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()
在这个整理后的代码中,主要进行了以下优化:

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-12 12:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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