使用 Beautiful Soup 在 python 中解析网页

问题描述 投票:0回答:3

我在从网站获取数据时遇到一些问题。网站源码在这里:

view-source:http://release24.pl/wpis/23714/%22La+mer+a+boire%22+%282011%29+FRENCH.DVDRip.XviD-AYMO

有这样的东西:

电影信息

Tytuł.............................................. : La mer à boire

Ocena......................................... ...: IMDB - 6.3/10 (24)

Produkcja...................................... ……:Franja

Gatunek....................................... ....: 戏剧

Czas 特瓦尼亚......................................: 98 分钟。

首映.........................................: 22.02 .2012 - Świat

Reżyseria.........................................:雅克·梅洛

Scenariusz................................................:Pierre Chosson、Jacques Maillot

Aktorzy........................................:丹尼尔·奥特伊、莫德惠勒,扬·特雷古埃, 阿兰·贝格尔

我想从这个网站获取数据以获得Python字符串列表:

[[Tytuł, "La mer à boire"]
[Ocena, "IMDB - 6.3/10 (24)"]
[Produkcja, Francja]
[Gatunek, Dramat]
[Czas trwania, 98 min.]
[Premiera, "22.02.2012 - Świat"]
[Reżyseria, "Jacques Maillot"]
[Scenariusz, "Pierre Chosson, Jacques Maillot"]
[Aktorzy, "Daniel Auteuil, Maud Wyler, Yann Trégouët, Alain Beigel"]]

我使用 BeautifulSoup 编写了一些代码,但我无法继续下去,我只是不知道从网站源代码中获取其余部分以及如何将其转换为字符串...... 请帮忙!

我的代码:

    # -*- coding: utf-8 -*-
#!/usr/bin/env python

import urllib2
from bs4 import BeautifulSoup

try :
    web_page = urllib2.urlopen("http://release24.pl/wpis/23714/%22La+mer+a+boire%22+%282011%29+FRENCH.DVDRip.XviD-AYMO").read()
    soup = BeautifulSoup(web_page)
    c = soup.find('span', {'class':'vi'}).contents
    print(c)
except urllib2.HTTPError :
    print("HTTPERROR!")
except urllib2.URLError :
    print("URLERROR!")
python beautifulsoup urllib
3个回答
14
投票

使用 BeautifulSoup 的秘诀是找到 HTML 文档的隐藏模式。例如,你的循环

for ul in soup.findAll('p') :
    print(ul)

方向正确,但它会返回所有段落,而不仅仅是您要查找的段落。然而,您正在寻找的段落具有类

i
的有用属性。在这些段落中,我们可以找到两个跨度,一个具有
i
类,另一个具有
vi
类。我们很幸运,因为这些跨度包含您正在寻找的数据:

<p class="i">
    <span class="i">Tytuł............................................</span>
    <span class="vi">: La mer à boire</span>
</p>

因此,首先获取具有给定类别的所有段落:

>>> ps = soup.findAll('p', {'class': 'i'})
>>> ps
[<p class="i"><span class="i">Tytuł... <LOTS OF STUFF> ...pan></p>]

现在,使用列表推导式,我们可以生成一个对列表,其中每对包含段落中的第一个和第二个跨度:

>>> spans = [(p.find('span', {'class': 'i'}), p.find('span', {'class': 'vi'})) for p in ps]
>>> spans
[(<span class="i">Tyt... ...</span>, <span class="vi">: La mer à boire</span>), 
 (<span class="i">Ocena... ...</span>, <span class="vi">: IMDB - 6.3/10 (24)</span>),
 (<span class="i">Produkcja.. ...</span>, <span class="vi">: Francja</span>),
 # and so on
]

现在我们有了跨度,我们可以从中获取文本:

>>> texts = [(span_i.text, span_vi.text) for span_i, span_vi in spans]
>>> texts
[(u'Tytu\u0142............................................', u': La mer \xe0 boire'),
 (u'Ocena.............................................', u': IMDB - 6.3/10 (24)'),
 (u'Produkcja.........................................', u': Francja'), 
  # and so on
]

这些文本仍然不好,但很容易纠正它们。要删除第一个点中的点,我们可以使用

rstrip()
:

>>> u'Produkcja.........................................'.rstrip('.')
u'Produkcja'

可以使用

:
:
删除
lstrip()

字符串
>>> u': Francja'.lstrip(': ')
u'Francja'

要将其应用于所有内容,我们只需要另一个列表理解:

>>> result = [(text_i.rstrip('.'), text_vi.replace(': ', '')) for text_i, text_vi in texts]
>>> result
[(u'Tytu\u0142', u'La mer \xe0 boire'),
 (u'Ocena', u'IMDB - 6.3/10 (24)'),
 (u'Produkcja', u'Francja'),
 (u'Gatunek', u'Dramat'),
 (u'Czas trwania', u'98 min.'),
 (u'Premiera', u'22.02.2012 - \u015awiat'),
 (u'Re\u017cyseria', u'Jacques Maillot'),
 (u'Scenariusz', u'Pierre Chosson, Jacques Maillot'),
 (u'Aktorzy', u'Daniel Auteuil, Maud Wyler, Yann Tr&eacute;gou&euml;t, Alain Beigel'),
 (u'Wi\u0119cej na', u':'),
 (u'Trailer', u':Obejrzyj zwiastun')]

就是这样。希望这个循序渐进的例子能让你更清楚地使用BeautifulSoup。


0
投票

这将为您提供您想要的列表,您必须编写一些代码来摆脱尾随的“....”并转换字符串。

    import urllib2
    from bs4 import BeautifulSoup

     try :
 web_page = urllib2.urlopen("http://release24.pl/wpis/23714/%22La+mer+a+boire%22+%282011%29+FRENCH.DVDRip.XviD-AYMO").read()
soup = BeautifulSoup(web_page)
LIST = []
for p in soup.findAll('p'):
    s = p.find('span',{ "class" : 'i' })
    t = p.find('span',{ "class" : 'vi' })
    if s and t:
        p_list = [s.string,t.string]
        LIST.append(p_list)

除了 urllib2.HTTPError : 打印(“HTTP错误!”) 除了 urllib2.URLError : 打印(“网址错误!”)


0
投票

这是干净的代码

import requests
from bs4 import BeautifulSoup

try:
    # Send an HTTP GET request to the URL
    url = "http://release24.pl/wpis/23714/%22La+mer+a+boire%22+%282011%29+FRENCH.DVDRip.XviD-AYMO"
    response = requests.get(url)

    # Check if the request was successful (status code 200)
    if response.status_code == 200:
        soup = BeautifulSoup(response.content, 'html.parser')

        # Find the span elements with class 'vi'
        vi_elements = soup.find_all('span', class_='vi')

        # Initialize a list to store the data
        data_list = []

        # Iterate through the 'vi' elements and extract the information
        for vi_element in vi_elements:
            # Extract the label and value as strings
            label = vi_element.find_previous('strong').get_text(strip=True)
            value = vi_element.get_text(strip=True)
            
            # Append the label and value as a list to the data_list
            data_list.append([label, value])

        # Print the data_list
        for item in data_list:
            print(item)
    else:
        print('Failed to retrieve the webpage. Status code:', response.status_code)

except requests.exceptions.RequestException as e:
    print('Error:', e)

此代码向指定的 URL 发送 HTTP GET 请求,解析 HTML 内容,找到“vi”元素,提取标签和值,并将它们存储在 data_list 中。最后,它打印数据列表,它应该类似于所需的格式。

参考: https://pytutorial.com/getting-website-source-using-python-requests

© www.soinside.com 2019 - 2024. All rights reserved.