【问题标题】:Beautiful Soup - Blank screen for a long time without any outputBeautiful Soup - 长时间黑屏没有任何输出
【发布时间】:2017-12-11 14:57:17
【问题描述】:

我对 python 很陌生,并且正在研究一个基于抓取的项目——我应该从包含特定搜索词的链接中提取所有内容并将它们放在一个 csv 文件中。作为第一步,我编写了这段代码来根据输入的搜索词从网站中提取所有链接。我只得到一个空白屏幕作为输出,我找不到我的错误。

import urllib
import mechanize
from bs4 import BeautifulSoup
import datetime

def searchAP(searchterm):
    newlinks = []
    browser = mechanize.Browser()
    browser.set_handle_robots(False)
    browser.addheaders = [('User-agent', 'Firefox')]
    text = ""
    start = 0

    while "There were no matches for your search" not in text:
        url = "http://www.marketing-interactive.com/"+"?s="+searchterm
        text = urllib.urlopen(url).read()
        soup = BeautifulSoup(text, "lxml")
        results = soup.findAll('a')
        for r in results:
            if "rel=bookmark" in r['href'] :
                newlinks.append("http://www.marketing-interactive.com"+ str(r["href"]))  
        start +=10
                return newlinks  
       print searchAP("digital marketing")

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    以下脚本根据给定的搜索关键字从网页中提取所有链接。但它并没有超出第一页的探索。尽管可以通过操纵 URL 中的页码轻松修改以下代码以从多个页面获取所有结果(如 Rutger de Knijfother answer 中所述)。

    from pprint import pprint
    import requests
    from BeautifulSoup import BeautifulSoup
    
    def get_url_for_search_key(search_key):
        base_url = 'http://www.marketing-interactive.com/'
        response = requests.get(base_url + '?s=' + search_key)
        soup = BeautifulSoup(response.content)
    
        return [url['href'] for url in soup.findAll('a', {'rel': 'bookmark'})]
    

    用法:

    pprint(get_url_for_search_key('digital marketing'))
    

    输出:

    [u'http://www.marketing-interactive.com/astro-launches-digital-marketing-arm-blaze-digital/',
     u'http://www.marketing-interactive.com/singapore-polytechnic-on-the-hunt-for-digital-marketing-agency/',
     u'http://www.marketing-interactive.com/how-to-get-your-bosses-on-board-your-digital-marketing-plan/',
     u'http://www.marketing-interactive.com/digital-marketing-institute-launches-brand-refresh/',
     u'http://www.marketing-interactive.com/entropia-highlights-the-7-original-sins-of-digital-marketing/',
     u'http://www.marketing-interactive.com/features/futurist-right-mindset-digital-marketing/',
     u'http://www.marketing-interactive.com/lenovo-brings-board-new-digital-marketing-head/',
     u'http://www.marketing-interactive.com/video/discussing-digital-marketing-indonesia-video/',
     u'http://www.marketing-interactive.com/ubs-melvin-kwek-joins-credit-suisse-as-apac-digital-marketing-lead/',
     u'http://www.marketing-interactive.com/linkedins-top-10-digital-marketing-predictions-2017/']
    

    希望这是您项目的第一步。

    【讨论】:

      【解决方案2】:

      你犯了四个错误:

      1. 您正在定义start,但您从未使用它。 (你也不能,据我在 http://www.marketing-interactive.com/?s=something 上看到的。没有基于 url 的分页。)所以你无休止地循环第一组结果。

      2. "There were no matches for your search" 不是该站点返回的无结果字符串。所以无论如何它都会一直持续下去。

      3. 您正在附加链接,包括 http://www.marketing-interactive.comhttp://www.marketing-interactive.com。所以你最终会得到http://www.marketing-interactive.comhttp://www.marketing-interactive.com/astro-launches-digital-marketing-arm-blaze-digital/

      4. 关于rel=bookmark 选择:arifs solution 是正确的选择。但如果你真的想这样做,你需要这样:

        for r in results:
            if r.attrs.get('rel') and r.attrs['rel'][0] == 'bookmark':
                newlinks.append(r["href"])
        

        这首先检查rel 是否存在,然后检查它的第一个孩子是否是"bookmark",因为r['href'] 根本不包含rel。 BeautifulSoup 的结构并非如此。

      要抓取此特定网站,您可以做两件事:

      1. 你可以用 Selenium 或其他支持 Javascript 的东西做一些事情,然后按下 "Load more" 按钮。但这很麻烦。

      2. 你可以利用这个漏洞:http://www.marketing-interactive.com/wp-content/themes/MI/library/inc/loop_handler.php?pageNumber=1&postType=search&searchValue=digital+marketing 这是提供列表的 url。它具有分页功能,因此您可以轻松地遍历所有结果。

      【讨论】:

      • 我已经纠正了你指出的错误,并在结果中使用了你的 sn-p - for r:如果 r.attrs.get('rel') 和 r.attrs['rel'] [0] == 'bookmark': newlinks.append(r["href"]) 仍然得到“按任意键继续”作为输出。甚至我代码中的 arif 书签解决方案也给出了相同的输出
      • 我已经使用 selenium(如你所建议的那样)来访问加载更多按钮。我确实在抓取新加载的链接时遇到了问题。你能看看吗? [stackoverflow.com/questions/45452281/…
      猜你喜欢
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 2019-03-06
      • 2018-01-14
      • 2018-05-07
      • 2013-04-25
      • 2023-01-13
      相关资源
      最近更新 更多