Python语法错误(w/soup)

2024-05-29 04:16:54 发布

您现在位置:Python中文网/ 问答频道 /正文

第1天用Python编码。还有汤。总的来说。 摘自《用Python进行Web抓取》一书:http://dl.finebook.ir/book/6f/13125.pdf

代码如下:

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
    try:
        html = urlopen(url)
    except HTTPError as e:
        return None
    try:
        bsObj = BeautifulSoup(html.read())
        title = bsObj.body.h1
    except AttributeError as e:
        return None
    return title
title = getTitle("http://www.pythonscraping.com/pages/page1.html")
if title == None:
    print("Title could not be found")
else:
    print(title)

这是错误:

File "<stdin>", line 12 title = getTitle("http://www.pythonscraping.com/pages/page1.html") Syntaxerror: invalid syntax

小帽子(^)在第一个标题的“e”下。你知道吗

使用python3.4,Soup 4。你知道吗

谢谢你的耐心。你知道吗


Tags: fromimportnonehttpurlreturntitlehtml
1条回答
网友
1楼 · 发布于 2024-05-29 04:16:54

如果您尝试通过Python命令行解释器执行该代码,则该代码将生成一个错误。即使代码在语法上符合Python语言规范,命令行解释器也会用错误标记该代码。你知道吗

在getTitle函数定义的结尾和第12行的后续调用之间添加空格可以解决问题。你知道吗

有关Python中函数定义的更多信息,请参阅以下文章:Python def function: How do you specify the end of the function?

相关问题 更多 >

    热门问题