【问题标题】:web scraping with beautiful soup用美丽的汤刮网
【发布时间】:2017-10-14 13:14:43
【问题描述】:

我有以下代码来提取最新的mac版MS office:

import urllib2
from bs4 import BeautifulSoup

quote_page = 'https://support.office.com/en-us/article/Update-history-
for-Office-2016-for-Mac-700cab62-0d67-4f23-947b-3686cb1a8eb7#bkmk_current'
page = urllib2.urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')
name_box = soup.find('p', attrs={'class': 'x-hidden-focus'})
print name_box

我正在尝试抓取 Office 2016 for Mac(所有应用程序)

15.39.0

我得到 None 作为输出。

感谢任何帮助。谢谢。

【问题讨论】:

  • 源码中没有x-hidden-focus
  • 有趣的是,当您右键单击元素时,似乎元素仅获得 x-hidden-focus 类(我猜您正在检查元素)。如果您导航到另一个p 而不右键单击它,然后右键单击它,您可以看到它的实际效果。
  • @dang,您的要求完全模糊。你能指定哪一行、哪张表、一个字符串或任何你想抓取的东西吗?

标签: python web-scraping beautifulsoup


【解决方案1】:

这行得通,解释在cmets中给出。

import requests
import bs4

url = 'https://support.office.com/en-us/article/Update-history-for-Office-2016-for-Mac-700cab62-0d67-4f23-947b-3686cb1a8eb7#bkmk_current'

table_id = 'tblID0EAGAAA'
resp= requests.get(url)

soup = bs4.BeautifulSoup(resp.text, 'lxml')

# find table that contains data of interest
table = soup.find('table', {'id' : table_id})

# get the second row in that table
second_row = table.findAll('tr')[1]

# get the second column in that row
second_column = second_row.findAll('td')[1]

# get the content in this cell
version = second_column.find('p').text

print(version)

【讨论】:

    【解决方案2】:

    一种不依赖于table id(很可能在每次发布后都会改变)或行顺序的解决方案:

    from bs4 import BeautifulSoup
    import requests
    import re
    
    page = requests.get('https://support.office.com/en-us/article/Update-history-or-Office-2016-for-Mac-700cab62-0d67-4f23-947b-3686cb1a8eb7#bkmk_current')
    pattern = re.compile(r'^Office.+Mac.*')
    
    version = BeautifulSoup(page.content, 'html.parser') \
                .select_one('section.ocpSection table tbody') \
                .find('p', text=pattern) \
                .parent \
                .find_next_sibling('td') \
                .select_one('p') \
                .text
    print(version)
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 2021-01-15
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2020-12-13
      • 2019-03-13
      相关资源
      最近更新 更多