python - BS4 python脚本运行时立即崩溃,但看代码应该没问题
问题描述
我写了以下代码。这可能不是最漂亮的,但我试过了。当我运行它时,它会创建 links.txt 文件,但实际脚本会立即崩溃,而不会在 cmd 上显示任何错误。我尝试研究 BS4,我真的认为这应该可行。
这是我试图开始工作的初始脚本,因此我最终可以将其更改为仅抓取“卡片”类中的链接,但事实上它甚至无法抓取我想了解我做错了什么的所有链接。
import requests
import time
from bs4 import BeautifulSoup
import sys
sys.stdout = open("links.txt", "a")
for x in range(0, 10):
try:
URL = f'https://wesbite.com/downloads/{x}/'
page = requests.get(URL)
time.sleep(5)
soup = BeautifulSoup(html, 'html.parser')
links_with_text = []
for a in soup.find_all('a', href=True):
if a.text:
links_with_text.append(a['href'])
print(links_with_text)
except:
continue
我最终尝试抓取的 Card 类的示例:
<div class="card-content">
<div class="center">
<a target="_blank" href="https://website.com/username/">username</a>
我接受了您的建议,删除了例外,并意识到我的缩进不一致。在修复该问题并更改 page.text 之后,它似乎可以工作。下面的代码:
import requests
import time
from bs4 import BeautifulSoup
import sys
sys.stdout = open("links.txt", "a")
for x in range(0, 10):
try:
URL = f'https://wesbite.com/downloads/{x}/'
page = requests.get(URL)
time.sleep(5)
soup = BeautifulSoup(page.text, 'html.parser')
links_with_text = []
for a in soup.find_all('a', href=True):
if a.text:
links_with_text.append(a['href'])
print(links_with_text)
except Exception as e:
print('something went wrong')
解决方案
html
变量 inBeautifulSoup(html, 'html.parser')
未在您发布的代码中定义,我的猜测是引发异常,该异常被您的块catch
抑制。删除try...catch
代码并运行它,异常是有用的信息,以这种方式抑制它们会阻止您发现问题。
推荐阅读
- ios - 使用 SwiftUI 的导航链接视图不是全屏
- r - 如何最小化创建的 R 代码的不可接受的长时间运行时间
- gcc - #line 上的 Clang 错误“预期表达式”(构建 gcc)
- spring - 用于在 REST API 上保存具有多个关系的实体的存储库与 JQPL
- amazon-web-services - 如何使用 AWS 设置绿/蓝部署管道?
- python - 验证时捕获 LDAPError
- postgresql - 在 cloudsql 实例上的所有数据库上启用 GCP 查询洞察
- python - 按熊猫中的一组分组
- visual-studio-2022 - Visual Studio 2022 在 Shift-F12 上打开 Bing.com
- unity3d - 如何修复 tilemap 插件奇怪的自动生成碰撞系统以实现统一(等距)