【问题标题】:Python 3 bs4 crawling links issue and list of dictionnaries problemPython 3 bs4 爬行链接问题和字典列表问题
【发布时间】:2020-12-29 21:54:43
【问题描述】:

我已经有一段时间没有爬网了,我在网站上被屏蔽了......

如果我用 chrome 检查页面,我会看到源代码中的所有链接,但是当使用 bs4 和 python 3 时,汤将不包含任何链接!

由于我是爬行新手,所以我希望有人向我解释一下:)

是代理的原因吗?这个页面是绝对不能爬的吗?

import requests
from bs4 import BeautifulSoup
import re

url="https://www.pointdevente.parionssport.fdj.fr/grilles/resultats"
request_headers={'User-Agent': "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6" }


r = requests.get(url,headers=request_headers)
req_txt=r.text
if r.status_code==200:
    soup = BeautifulSoup(req_txt, u'html5lib')
    print(soup.prettify())
    links_pak=[url + u'/' + node.get(u'href') for node in soup.find_all(u'a')] #if node.get(u'href').endswith(ext)]
    print("links : ",links_pak)
else:
    print(r.status_code)

编辑:经过一些研究,我发现这是由于 JS 前端代码,所以我查看了网络行为并发现了一些我应该能够用于我需要的 API 调用。

所以这是我的字典问题列表,所以我有以下代码:

import requests
from bs4 import BeautifulSoup
import re

url="https://www.pointdevente.parionssport.fdj.fr/api/loto-foot/list"

r = requests.get(url)
req_txt=r.text
if r.status_code==200:
    print(r.json())
    list_all=r.json()

else:
    print(r.status_code)

我查看了很多文档,并且我了解如何根据键值过滤字典或查看字典列表中是否有值,但我想要检查我的字典列表(例如 list_all)是否有字典中的键:值元组,如果是,则仅检索此字典的数据!

在我的示例中,如果您运行代码片段,您将在 dicts 中看到“sportId”键,我只想在“sportId:100”为真时获取 dicts...我有点困惑听写理解....

感谢您的帮助!

【问题讨论】:

  • 可能你应该看看具有自动化功能的全功能网络浏览器 (selenium-python?),因为许多网站通过 JavaScript 请求 (XMLHttpRequest) 获取数据,这可能很难通过 requests/ curl/wget。在您的情况下,请查看 url pointdevente.parionssport.fdj.fr/api/loto-foot/…
  • 是的,我发现了这个 api 地址,我不知道我是否会使用它或只匹配来 :) 我仍然不知道如何选择对我有用的词典 :( ((我编辑了我的帖子以解释更多细节。

标签: python python-3.x beautifulsoup web-crawler


【解决方案1】:

好的,经过多次列表理解尝试后,我发现了如何做......

所以这里的代码 sn-p 工作:

import requests
from bs4 import BeautifulSoup
import re

url="https://www.pointdevente.parionssport.fdj.fr/api/loto-foot/list"

r = requests.get(url)
req_txt=r.text
if r.status_code==200:
    list_all=r.json()
    list_foot=[d for d in list_all if d['sportId']==100] #Filters foot results only
    print(list_foot)

else:
    print(r.status_code)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2014-06-10
    • 2021-11-11
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多