首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BS4选择()方法

BS4选择()方法
EN

Stack Overflow用户
提问于 2017-11-09 06:49:14
回答 1查看 3K关注 0票数 0

这是我从wordinastence.com中抓取和解析必要信息的代码,它为给定的单词提供了有用的上下文语句:

代码语言:javascript
复制
#first import request to crawl the html from the target page
#this case the website is http://www,wordinasentence.com

import requests

target = input("The word you want to search : ")

res = requests.get("https://wordsinasentence.com/"+ target+"-in-a-sentence/")

#further, put this in so that res_process malfunction could flag the errors
try:
    res.raise_for_status()
except Exception as e:
    print("There's a problem while connecting to a wordsinasentence sever:", e)

#it's a unreadable information, so that we needs to parse it to make it readable.
## use the beautifulsoup to make it readable

import bs4
html_soup = bs4.BeautifulSoup(res.text, 'html.parser')

#check it has been well parsed
#now we'll extract the Defintion of target

keywords = html_soup.select('Definition')

如果我运行给定的方法select('Defintion'),即使使用html_soup变量打印的以下内容,它仍然不返回空列表:

代码语言:javascript
复制
<p onclick='responsiveVoice.speak("not done for any particular reason; chosen or done at random");' style="font-weight: bold; font-family:Arial; font-size:20px; color:#504A4B;padding-bottom:0px;">Definition of Arbitrary</p>

[]

可能的问题是什么?

EN

回答 1

Stack Overflow用户

发布于 2017-11-09 20:05:32

问题是您使用了错误的方法来查找文本(select()是为css选择器创建的)。您可以使用带有stringfind_all和一个函数来选择要查找的标记。

代码语言:javascript
复制
def has_text_def(s):    
    return s and s.startswith('Definition of')

definitions = soup.find_all('p', string=has_text_def)

顺便说一句,您需要获得)来访问定义:

代码语言:javascript
复制
for p in definitions:
    print(p.next_sibling.next_sibling.text)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47195598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档