python-3.x - 在 Python 中对 BeautifulSoup 使用 FOR 循环和 IF
问题描述
我正在尝试提取一些网页的元描述。下面是我的代码:
URL_List = ['https://digisapient.com', 'https://dataquest.io']
Meta_Description = []
for url in URL_List:
response = requests.get(url, headers=headers)
#lower_response_text = response.text.lower()
soup = BeautifulSoup(response.text, 'lxml')
metas = soup.find_all('meta')
for m in metas:
if m.get ('name') == 'description':
desc = m.get('content')
Meta_Description.append(desc)
else:
desc = "Not Found"
Meta_Description.append(desc)
现在这将返回给我以下内容:
['Not Found',
'Not Found',
'Not Found',
'Not Found',
'Learn Python, R, and SQL skills. Follow career paths to become a job-qualified data scientist, analyst, or engineer with interactive data science courses!',
'Not Found',
'Not Found',
'Not Found',
'Not Found']
我想把content
元数据拉到哪里name == 'description'
。如果条件不匹配,即页面没有元属性,name == 'description
它应该返回Not Found
。
预期输出:
['Not Found',
'Learn Python, R, and SQL skills. Follow career paths to become a job-qualified data scientist, analyst, or engineer with interactive data science courses!']
请建议。
解决方案
让我知道这是否适合您!
URL_List = ['https://digisapient.com', 'https://dataquest.io']
Meta_Description = []
meta_flag = False
for url in URL_List:
response = requests.get(url, headers=headers)
meta_flag = False
#lower_response_text = response.text.lower()
soup = BeautifulSoup(response.text, 'lxml')
metas = soup.find_all('meta')
for m in metas:
if m.get ('name') == 'description':
desc = m.get('content')
Meta_Description.append(desc)
meta_flag = True
continue
if not meta_flag:
desc = "Not Found"
Meta_Description.append(desc)
代码背后的想法是,它将遍历 中的所有项目metas
,如果找到“描述”,它将将该标志设置为 True,从而跳过后续的 if 语句。如果在迭代之后metas
没有找到任何东西,它会将“未找到”附加到Meta_Description
.
推荐阅读
- android - 检测当前是否正在显示最近的应用程序(又名概览屏幕)
- java - 将文件从目录复制到手机内部存储的另一个目录时出错?
- google-bigquery - bigquery 嵌套对象:没有这样的字段
- java - XWPF 删除第一页
- java - 带属性的弹簧单例
- unit-testing - 等价分区
- ruby-on-rails - 如何通过发布请求防止 ruby on rails 中的 SQL 注入
- spring - GET 类型的 REST 服务的 DTO 映射
- php - Laravel 5.6 使用 Ajax 登录后无法访问用户详细信息
- apache-spark - 使用直线连接到 Spark Thrift 服务器的问题