python - 修复包含漂亮汤方法的列表推导的语法错误
问题描述
我很努力,但后面的代码总是有一些语法错误。
import urllib.request
import re
import csv
from bs4 import BeautifulSoup
from bs4 import NavigableString
from unicodedata import normalize
url = input('Please paste the link here: ')
html = urllib.request.urlretrieve(url)
html_file = open(html[0])
soup = BeautifulSoup(html_file, 'html5lib')
def contains_href(tag):
return tag.find('a', href=True)
scrollables = [table in soup.find_all('table', class_='sc_courselist') if contains_href(table)]
def num_name_unit(tag):
td_num = tag.find('td', href=True)
num = normalize('NFKD', td_num.string.strip())
td_name = tag.find('td', class_=False)
name = normalize('NFKD', td_name.string.strip())
td_unit = tag.find('td', class_='hourscol')
unit = normalize('NFKD', td_unit.string.strip())
row = ['Course Number: {0} | Course Name: {1} | Course Unit: {2}'.format(num, name, unit)]
return row
dic_rows = {scrollable.find_previous_siblings(re.compile('h'), class_=False, limit=1).string.strip(): list(num_name_unit(tr) for tr in scrollable.find_all('tr', contains_href)) for scrollable in scrollables}
我希望终端会打印以下请求:“请在此处粘贴链接:”。实际上,它在 scrollables = [table in soup.find_all('table', class_='sc_courselist') if contains_href(table)] 末尾显示“无效语法”。
解决方案
您缺少列表中的 for 部分。它应该是
[table for table in soup.find_all('table', class_='sc_courselist') if contains_href(table)]
推荐阅读
- c# - 如何在我的 xaml 页面中调用构造函数?
- python - pandas Series 是一个乳胶对象:如何转换回正常的 pd.Series()?
- maven - 从 docker 文件运行 testng xml 时的未知生命周期阶段“全新安装测试 -Dsurefire.suiteXmlFiles=testng.xml”
- java - com.facebook.react.bridge.NativeArgumentsParseException:RNGooglePlaces.openAutocompleteModal 有 3 个参数,预期为 4
- sql - 如何使用 BigQuery 显示自联接的树层次结构表?
- sql - 我试图让 Max 函数工作,但它返回 null 后跟十进制数
- ios - 在 iOS 上升级应用程序时重置位置服务权限
- c# - MStest > OpenQA.Selenium.DriverServiceNotFoundException
- ionic-framework - 离子 3.9 本地通知和 androidx
- botframework - 如何设置用于测试的机器人和用于生产的机器人?