python - 解析器不写入 json。仅写入 {}
问题描述
我为自己的目的创建了一个市场解析器,它总体上运行良好!
最初遇到一个录制问题,给了一个解码错误。现在他做了一些事情,它消失了,但现在他不想将数据解析成json,而只是写了2个字符 - {}
这是main.py:
import json
import requests
from bs4 import BeautifulSoup
def get_first_news():
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36"
}
url = "https://funpay.ru/lots/700/"
r = requests.get(url=url, headers=headers)
soup = BeautifulSoup(r.text, "lxml")
articles_cards = soup.find_all("a", class_="tc-desc-text")
news_dict = {}
for article in articles_cards:
article_title = article.find("div", class_="tc-desc-text").text.strip()
article_desc = article.find("div", class_="tc-price").text.strip()
article_url = f'https://funpay.ru/lots/700/{article.get("href")}'
article_id = article_url.split("=")[-1]
# print(f"{article_title} | {article_url} | {article_date_timestamp}")
news_dict[article_id] = {
"article_title": article_title,
"article_url": article_url,
"article_desc": article_desc
}
with open("news_dict.json", "w") as file:
json.dump(news_dict, file, indent=4, ensure_ascii=False)
def main():
get_first_news()
if __name__ == '__main__':
main()
这是test.py
# url = "https://www.securitylab.ru/news/520908.php"
#
# article_id = url.split("/")[-1]
# article_id = article_id[:-4]
# print(article_id)
import json
with open("news_dict.json") as file:
news_dict = json.load(file)
search_id = "520908123"
if search_id in news_dict:
print("Новость уже есть в словаре, пропускаем итерацию")
else:
print("Свежая новость, добавляем в словарь")
这是 news_dict.json:
{}
解决方案
在 article_cards = soup.find_all ("a", class _ = "tc-desc-text") 中,我们将 "a" 替换为 "div" 以下是应该出来的内容: article_cards = soup.find_all ("div", class _ =“tc-desc-文本”)
推荐阅读
- java - MyBatis Generator 无法实例化自定义插件类
- python - 如何猴子补丁django功能?
- java - 如何从 Intent 遍历自定义对象的 ArrayList 并将它们添加到 LinearLayout?
- javascript - nodejs - Set-Cookie 出现在响应中但在浏览器中丢失
- javascript - 从 href 调用 javascript 函数
- node.js - 使用节点 js 将 aac 文件写入光盘
- kubernetes - FailedScheduling:0/3 个节点可用:3 个 Pod 不足
- python - 使用 pandas groupby 查找列最大值的日期和值
- c++ - 可以在 lambda 运行之前使 lambda 捕获的 [this] 指针无效吗?
- python - 是否可以计算 AWS s3 对象的 sha256 或 sha1 哈希?