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)
Pet*_*ann 57
我会一直使用lxml来完成这些任务.你也可以使用beautifulsoup.
import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text
Run Code Online (Sandbox Code Playgroud)
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)
使用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)
使用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)
无需导入其他库.请求具有内置的此功能.
>> 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)
使用正则表达式
import re
match = re.search('<title>(.*?)</title>', raw_html)
title = match.group(1) if match else 'No title'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
72444 次 |
最近记录: |