【问题标题】:Crawling links in a div抓取div中的链接
【发布时间】:2016-12-18 02:37:00
【问题描述】:

我正在使用 Beautiful Soup 在 Python 中制作网络爬虫。我想从某个 div 获取链接,我现在的代码不打印任何东西。

import requests
from bs4 import BeautifulSoup

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'https://thenewboston.com/'
        source = requests.get(url)
        plain_text = source.text
        obj = BeautifulSoup(plain_text, "html5lib")

        for link in obj.find_all('div', {'class': 'videos-top-courses'}):
            href = 'https://thenewboston.com/', link.get('href')
            print(href)
        page += 1

spider(1)

【问题讨论】:

  • 在这个链接里看答案希望对你有帮助=stackoverflow.com/questions/28390593/…
  • &lt;div&gt; 没有href - 你必须找到&lt;a&gt;
  • 没有('div', {'class': 'videos-top-courses'}),查看源码
  • 查看您正在访问的 URL 中的 HTML,该类没有 &lt;div&gt;s - 只有 &lt;table&gt; 元素,因此您的 find_all 调用(正确)不返回任何元素.
  • 没有&lt;div&gt;class="videos-top-courses"。有&lt;table&gt;class="videos-top-courses"

标签: python request beautifulsoup web-crawler bs4


【解决方案1】:

你必须找到&lt;table&gt;而不是&lt;div&gt;,然后你可以找到&lt;a&gt;来获得href

import requests
from bs4 import BeautifulSoup

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'https://thenewboston.com/'
        source = requests.get(url)
        plain_text = source.text
        obj = BeautifulSoup(plain_text, "html5lib")

        for table in obj.find_all('table', {'class': 'videos-top-courses'}):
            for a in table.find_all('a'):
                print(a.get('href'))
        page += 1

spider(1)

【讨论】:

  • 这行得通,更接近我想要的,但它会打印出 3 个相同的链接。
  • 这就是我使用video-icon-column作为类的原因
  • 每个视频描述中有 3 个&lt;a&gt; - (1) 图像中,(2) 标题中,(3) 描述下方的视频数量。您必须在 find_all 中使用其他参数才能仅获得一个 &lt;a&gt; - 请参阅其他答案 - 或使用索引 [0] 仅获得一个 &lt;a&gt; - 即。 a = table.find_all('a')[0]
  • 当我这样做时,它会多次打印出一个链接。
【解决方案2】:

你可以使用类似的东西:

from bs4 import BeautifulSoup
from urllib2 import urlopen
soup = BeautifulSoup(urlopen("https://thenewboston.com/"),'html.parser')
videos = soup.findAll('td', {'class': 'video-icon-column'})
for td in videos:
    print td.a['href']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2016-01-23
    相关资源
    最近更新 更多