【问题标题】:Improving a python snippet改进python片段
【发布时间】:2014-04-18 14:49:04
【问题描述】:

我正在编写一个 python 脚本来进行网络抓取。我想在网页上找到给定部分的基本 URL,如下所示:

<div class='pagination'>
    <a href='webpage-category/page/1'>1</a>
    <a href='webpage-category/page/2'>2</a>
    ...
</div>

所以,我只需要从第一个 href 中获取除 number('webpage-category/page/') 之外的所有内容,并且我有以下工作代码:

pages = [l['href'] for link in soup.find_all('div', class_='pagination')
     for l in link.find_all('a') if not re.search('pageSub', l['href'])]

s = pages[0]
f = ''.join([i for i in s if not i.isdigit()])

问题是,生成这个列表是一种浪费,因为我只需要第一个 href。我认为发电机会是答案,但我无法做到这一点。也许你们可以帮助我使这段代码更简洁?

【问题讨论】:

    标签: python html web-scraping html-parsing beautifulsoup


    【解决方案1】:

    这个呢:

    from bs4 import BeautifulSoup
    
    html = """ <div class='pagination'>
        <a href='webpage-category/page/1'>1</a>
        <a href='webpage-category/page/2'>2</a>
    </div>"""
    
    soup = BeautifulSoup(html)
    
    link = soup.find('div', {'class': 'pagination'}).find('a')['href']
    
    print '/'.join(link.split('/')[:-1])
    

    打印:

    webpage-category/page
    

    仅供参考,谈谈您提供的代码 - 您可以使用 [next()][-1] 而不是列表推导:

    s = next(l['href'] for link in soup.find_all('div', class_='pagination')
             for l in link.find_all('a') if not re.search('pageSub', l['href']))
    

    UPD(使用提供的网站链接):

    import urllib2
    from bs4 import BeautifulSoup
    
    
    url = "http://www.hdwallpapers.in/cars-desktop-wallpapers/page/2"
    soup = BeautifulSoup(urllib2.urlopen(url))
    
    links = soup.find_all('div', {'class': 'pagination'})[1].find_all('a')
    
    print next('/'.join(link['href'].split('/')[:-1]) for link in links 
               if link.text.isdigit() and link.text != "1")
    

    【讨论】:

    • 好吧,你几乎明白了。但实际上该页面有两个“分页”div,一个具有以下结构(“webpage-category/pageSub/1”)。这个我不感兴趣,所以我通过重新丢弃它。你能把所有这些都放在一个衬里吗?
    • @XVirtusX 好的,当然。你能告诉我相关的html或网站链接吗?我很确定该任务可以以比href 使用正则表达式过滤链接更简洁的方式完成。谢谢。
    • @XVirtusX 查看更新:我只是获取页面上的最后一个分页 div,然后获取所有链接,然后从包含数字和文本的链接中提取基本 url不等于1(因为第一页有不同的基本网址)。
    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多