Python 最近在 3.10 版本中发布了 match-case。问题是我们如何在 Python 中实现默认情况?我可以做if/elif
,但不知道还能做什么。下面是代码:
x = "hello"
match x:
case "hi":
print(x)
case "hey":
print(x)
default:
print("not matched")
Run Code Online (Sandbox Code Playgroud)
这是我default
自己添加的。我想知道在 Python 中执行此操作的方法。
我正在向某个 URL 发送请求。我将curl命令复制到python中。因此,所有标头都包含在内,但我的请求不起作用,并且我在 HTML 输出中收到状态代码 403 和错误代码 1020。
代码是
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:106.0) Gecko/20100101 Firefox/106.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
# 'Accept-Encoding': 'gzip, deflate, br',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
}
response = requests.get('https://v2.gcchmc.org/book-appointment/', headers=headers)
print(response.status_code)
print(response.cookies.get_dict())
with open("test.html",'w') as f:
f.write(response.text)
Run Code Online (Sandbox Code Playgroud)
我也收到了 cookie,但没有得到所需的响应。我知道我可以用硒做到这一点,但我想知道这背后的原因。
注意:
我已经安装了所有库并检查了版本,但它仍然无法工作并抛出 403 错误。
即使脚本未正常退出,我也尝试关闭浏览器。我尝试了一些在互联网上找到的方法但未能成功。首先是使用 try/ except 和finally。我实现了它,但如果强制停止脚本执行,则不起作用。我已经复制了我的代码。如果使用 chrome,它不会在强制退出时关闭浏览器。Firefox 正在正常关闭。代码分为两个文件(scraper.py、initialize.py)
刮刀.py
try:
from .initialize import Init
except:
from initialize import Init
import time
URL = "https://web.whatsapp.com/"
def main(driver):
# do parsing and other stuff
driver.get(URL)
time.sleep(15)
def get_driver(browser, headless):
# calling start drivers method of init class from initialize file
return Init(method='profile',write_directory='output/',selenium_wire=True,undetected_chromedriver=True,old_profile_using=False).start_driver(browser=browser, url=URL, headless=headless, refresh=True)
try:
driver = get_driver("firefox" , False)
main(driver)
# get_driver returns driver.
except Exception as e:
print(f"Error: {e}")
finally:
try:
driver.quit()
except NameError:
pass
Run Code Online (Sandbox Code Playgroud)
初始化.py
from selenium import webdriver
from …
Run Code Online (Sandbox Code Playgroud)