【问题标题】:BeautifulSoup gets nothing between tagsBeautifulSoup 在标签之间一无所获
【发布时间】:2017-10-10 07:57:24
【问题描述】:

我是一个写网络爬虫的新手。我想使用http://www.creditchina.gov.cn/search_all#keyword=&searchtype=0&templateId=&creditType=&areas=&objectType=2&page=1 的搜索引擎来检查我的输入是否有效。

例如,912101127157655762 是有效输入,912101127157655760 是无效输入。

通过开发者工具查看网页源代码后,我发现如果输入的是无效数字,则标签为:

如果输入有效,则标签为:

所以我想通过检查'ul class=“credit-info-results public-results-left item-template”'标签中是否有任何内容来确定输入是否有效。以下是我编写网络爬虫的方式:

import urllib
from bs4 import BeautifulSoup
url = 'http://www.creditchina.gov.cn/search_all#keyword=912101127157655762&searchtype=0&
templateId=&creditType=&areas=&objectType=2&page=1'
req = urllib.request.Request(url)
data = urllib.request.urlopen(req)
bs = data.read().decode('utf-8')
soup = BeautifulSoup(bs, 'lxml')
check = soup.find_all("ul", {"class": "credit-info-results public-results-left item-template"})
if check == []:
    # TODO
if check != []:
    # TODO

但是,check 的值始终是 []。我不明白为什么选项卡之间没有任何内容。希望有人可以帮助我解决问题。

【问题讨论】:

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


    【解决方案1】:

    你得到的不是 html 而是 JS 对象作为响应。这就是为什么BS无法解析它。

    您可以使用子字符串搜索来检查响应是否包含某些内容。

    import urllib
    from bs4 import BeautifulSoup
    url = 'http://www.creditchina.gov.cn/search_all#keyword=912101127157655762&searchtype=0&
    templateId=&creditType=&areas=&objectType=2&page=1'
    req = urllib.request.Request(url)
    data = urllib.request.urlopen(req)
    bs = data.read().decode('utf-8')
    
    ul_pos = bs.find('credit-info-results public-results-left item-template')
    if ul_pos <> 0:
      bs = bs[ul_pos:]
    
    soup = BeautifulSoup(bs, 'lxml')
    check = soup.find_all("ul", {"class": "credit-info-results public-results-left item-template"})
    if check == []:
        # TODO
    if check != []:
        # TODO
    

    【讨论】:

    • 我如何知道我是否得到了 html 而不是 JS 对象?另外,我检查了 bs.find('credit-info-results public-results-left item-template') 的值是 39202,输入 912101127157655762 和 912101127157655760 应该返回不同的输出值。这令人困惑......
    • 我已经更新了我的答案,请尝试一下。不幸的是,我不能自己测试它,因为这个网站禁止了我的请求。
    • 我发现我得到的只是一个网络模板。而且我需要查看网络而不是开发人员工具的元素。无论如何,感谢您的时间和耐心!
    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 2023-04-04
    • 1970-01-01
    • 2017-12-25
    • 2018-01-02
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    相关资源
    最近更新 更多