python - 按照论坛中的链接使用 BS4 抓取线程(评论)
问题描述
我有一个有 3 个线程的论坛。我正在尝试抓取所有三个帖子中的数据。所以我需要按照每个帖子的href链接并抓取数据。这给了我一个错误,我不确定我错了什么......
import csv
import time
from bs4 import BeautifulSoup
import requests
source = requests.get('https://mainforum.com').text
soup = BeautifulSoup(source, 'lxml')
#get the thread href (thread_link)
for threads in soup.find_all('p', class_= 'small'):
thread_name = threads.text
thread_link = threads.a.get('href')# there are three threads and this gets all 3 links
print (thread_link)
其余代码是我遇到问题的地方?
# request the individual thread links
for follow_link in thread_link:
response = requests.get(follow_link)
#parse thread link
soup= BeautifulSoup(response, 'lxml')
#print Data
for p in soup.find_all('p'):
print(p)
解决方案
至于您的架构错误...
您收到架构错误,因为您一遍又一遍地覆盖一个链接。然后您尝试调用该链接,就好像它是链接列表一样。此时它是一个字符串,您只需遍历字符(以 开头h
)因此出现错误。
请参阅此处:requests.exceptions.MissingSchema:无效的 URL 'h':未提供架构
至于一般查询以及如何解决这样的问题......
如果我要这样做,流程将如下所示:
- 获取三个href(类似于您已经完成的)
- 使用一个函数单独抓取线程href并返回您希望它们返回的任何内容
- 将返回的信息保存/附加到您想要的任何位置。
- 重复
可能是这样的
import csv
import time
from bs4 import BeautifulSoup
import requests
source = requests.get('https://mainforum.com')
soup = BeautifulSoup(source.content, 'lxml')
all_thread_info = []
def scrape_thread_link(href):
response = requests.get(href)
#parse thread link
soup= BeautifulSoup(response.content, 'lxml')
#return data
return [p.text for p in soup.find_all('p')]
#get the thread href (thread_link)
for threads in soup.find_all('p', class_= 'small'):
this_thread_info = {}
this_thread_info["thread_name"] = threads.text
this_thread_info["thread_link"] = threads.a.get('href')
this_thread_info["thread_data"] = scrape_thread_link(this_thread_info["thread_link"])
all_thread_info.append(this_thread_info)
print(all_thread_info)
原始问题中有很多未指定的内容,所以我做了一些假设。理想情况下,尽管您可以看到要点。
另请注意,我更喜欢使用.content
ofresponse
而不是.text
。
推荐阅读
- php - PHP JQuery Ajax $_FILES['file'] 未定义索引错误
- c++ - 奇怪的类似我的世界的地形生成
- laravel - 在 Laravel 框架中执行 VueJS 组件的服务器端表单验证的惯用方式?
- npm - Package-lock.json 文件未在分支中正确安装 npm
- vim - VIM:在 VHDL 中对齐列
- html - 如何在 angularjs 中正确使用 ng-class?
- r - 使用 chrome_print 将 pagedown html_resume 编织为 pdf 会产生错误
- ios - UISearchResultsUpdating 不符合视图控制器中的扩展类
- xslt-2.0 - XSLT 用点分隔字符转换字符串
- reactjs - 使 div 可编辑并以表单形式捕获值,就好像它是文本区域一样