Python 如何在没有正则表达式的情况下编写以下代码
我编写了以下代码,用于从网页中提取所有编号并添加所有编号。但我想在不使用正则表达式的情况下对其进行编码,因此,请指导我如何操作。 链接: 我的代码:Python 如何在没有正则表达式的情况下编写以下代码,python,web,beautifulsoup,numbers,extract,Python,Web,Beautifulsoup,Numbers,Extract,我编写了以下代码,用于从网页中提取所有编号并添加所有编号。但我想在不使用正则表达式的情况下对其进行编码,因此,请指导我如何操作。 链接: 我的代码: import urllib import re from BeautifulSoup import * html = urllib.urlopen('http://python-data.dr-chuck.net/comments_361585.html ').read() soup = BeautifulSoup(html) # Retri
import urllib
import re
from BeautifulSoup import *
html = urllib.urlopen('http://python-data.dr-chuck.net/comments_361585.html ').read()
soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags = soup('td')
total = 0
for tag in tags:
# Look at the parts of a tag
line = str(tag)
x = re.findall('[0-9]+',line)
if len(x) > 0:
for item in x:
total += int(item)
print(total)
在不使用regex的情况下,我尝试了以下方法:
import urllib
from BeautifulSoup import *
url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
tags = soup.find_all('span', text=True)
for tag in tags:
number=tag.get('class', None)
total = sum( int(tag.text) for tag in tags )
print ('total')
但它有一些错误:“NoneType”对象是不可调用的
请指导我如何修复它。您根本不必使用正则表达式,只需使用bs4即可轻松完成此操作。
您可以搜索“span”,而不是获取所有“td”并使用正则表达式过滤它们的值:
tags = soup.find_all('span', text=True)
然后您可以将结果相加:
total = sum( int(tag.text) for tag in tags )
你应该自己做作业……我已经做了……我想知道第二条路