如何使用Python检索网页的页面标题?

csc*_*hol 68 html python

如何使用Python检索网页的页面标题(标题html标记)?

jfs*_*jfs 83

这是@Vinko Vrsalovic答案的简化版本:

import urllib2
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen("https://www.google.com"))
print soup.title.string
Run Code Online (Sandbox Code Playgroud)

注意:

  • soup.title在html文档中的任何位置找到第一个title元素

  • title.string假定它只有一个子节点,并且该子节点是一个字符串

对于beautifulsoup 4.x,使用不同的导入:

from bs4 import BeautifulSoup
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!如果有人遇到类似的问题,在我的Python3环境中,我不得不使用`urlllib.request`而不是`urllib2`.不知道为什么.为了避免关于我的解析器的BeautifulSoup警告,我不得不做`汤= BeautifulSoup(urllib.request.urlopen(url),"lxml")`. (7认同)

Pet*_*ann 57

我会一直使用lxml来完成这些任务.你也可以使用beautifulsoup.

import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text
Run Code Online (Sandbox Code Playgroud)

  • 以防您使用上面的代码获得IOError:http://stackoverflow.com/questions/3116269/error-with-parse-function-in-lxml (4认同)
  • [lxml 可能存在 Unicode 问题](http://stackoverflow.com/q/15302125/4279),您可以[使用 bs4.UnicodeDammit 帮助它找到正确的字符编码](http://stackoverflow.com/a /15305248/4279) (2认同)

cod*_*ape 13

mechanize Browser对象有一个title()方法.所以这篇文章的代码可以改写为:

from mechanize import Browser
br = Browser()
br.open("http://www.google.com/")
print br.title()
Run Code Online (Sandbox Code Playgroud)


Vin*_*vic 10

这对于这样一个简单的任务来说可能有点过头了,但是如果你打算做更多的事情,那么从这些工具(机械化,BeautifulSoup)开始是更合理的,因为它们比替代品更容易使用(urllib来获取内容和regexen)或其他一些解析html的解析器)

链接: BeautifulSoup 机械化

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

from BeautifulSoup import BeautifulSoup
from mechanize import Browser

#This retrieves the webpage content
br = Browser()
res = br.open("https://www.google.com/")
data = res.get_data() 

#This parses the content
soup = BeautifulSoup(data)
title = soup.find('title')

#This outputs the content :)
print title.renderContents()
Run Code Online (Sandbox Code Playgroud)


QHa*_*arr 8

使用soup.select_one 来定位标题标签

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('url')
soup = bs(r.content, 'lxml')
print(soup.select_one('title').text)
Run Code Online (Sandbox Code Playgroud)


Fin*_*inn 5

使用HTMLParser:

from urllib.request import urlopen
from html.parser import HTMLParser


class TitleParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.match = False
        self.title = ''

    def handle_starttag(self, tag, attributes):
        self.match = True if tag == 'title' else False

    def handle_data(self, data):
        if self.match:
            self.title = data
            self.match = False

url = "http://example.com/"
html_string = str(urlopen(url).read())

parser = TitleParser()
parser.feed(html_string)
print(parser.title)  # prints: Example Domain
Run Code Online (Sandbox Code Playgroud)


Rah*_*wla 5

无需导入其他库.请求具有内置的此功能.

>> hearders = {'headers':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0'}
>>> n = requests.get('http://www.imdb.com/title/tt0108778/', headers=hearders)
>>> al = n.text
>>> al[al.find('<title>') + 7 : al.find('</title>')]
u'Friends (TV Series 1994\u20132004) - IMDb' 
Run Code Online (Sandbox Code Playgroud)


Fin*_*inn 5

使用正则表达式

import re
match = re.search('<title>(.*?)</title>', raw_html)
title = match.group(1) if match else 'No title'
Run Code Online (Sandbox Code Playgroud)