import requests import os from bs4 import BeautifulSoup cookie = os.getenv('MY_COOKIE') # 保存到环境变量中 def get_with_cookie(url): headers = { 'cookie': cookie, 'pragma': 'no-cache', 'referer': 'https://uland.taobao.com/sem/tbsearch?refpid=mm_26632258_3504122_32538762&keyword=%E7%88%B1%E6%B7%98%E5%AE%9D%E4%B9%B0%E4%B8%9C%E8%A5%BF&clk1=066356e5e429004e6730976351cc1afc&upsId=066356e5e429004e6730976351cc1afc', 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': "Windows", 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'same-origin', 'sec-fetch-user': '?1', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.50' } try: resp = requests.get(url=url, headers=headers) return resp.text except requests.exceptions.RequestException as e: print("请求异常:", e) return None # 解析HTML内容,提取商品名称、价格和销量信息 def parse_html(html): try: soup = BeautifulSoup(html, 'html.parser') title = soup.select_one('h3.tb-main-title[data-title]') return title except Exception as e: print("解析异常:", e) return None # 测试接口: url = 'https://item.taobao.com/item.htm?id=699089474285&ali_refid=a3_430673_1006:1102522391:N:%2BAkz14GC%2BXi%2Bma9dw7y9M4p5Yhq5iT8I:f9e826228fbc823934848d20e28dff81&ali_trackid=162_f9e826228fbc823934848d20e28dff81&spm=a2e0b.20350158.31919782.5' resp_text = get_with_cookie(url) if resp_text is not None: title = parse_html(resp_text) if title is not None: # 打印商品信息 print(title.text.strip()) else: print("解析失败") else: print("请求失败")在捕获异常时打印出完整的错误信息,以便更好地排查问题
时间: 2023-11-29 08:05:37 浏览: 102
import sys import os import urllib from bs4 import BeautifulSoup
好的,将异常捕获部分修改为以下代码即可:
```
except Exception as e:
print(f"解析异常: {e}\n{traceback.print_exc()}")
```
这样就可以在捕获到异常时,打印出完整的错误信息和堆栈信息,方便排查问题。需要注意的是,需要先在代码开头引入 `traceback` 模块。
阅读全文