如何获取没有 HTML 标签的文本 |在拆分中添加多个分隔符

How to get text which has no HTML tag | Add multiple delimiters in split

在 XPath select div 元素之后使用 class ajaxcourseindentfix 并将其从先决条件中分离出来,并在先决条件之后为我提供所有内容。

div = soup.select("div.ajaxcourseindentfix")[0]
" ".join([word for word in div.stripped_strings]).split("Prerequisite: ")[-1]

我的div不仅可以有前提,还可以有以下分裂点:

Prerequisites
Corerequisite
Corerequisites

现在,每当我有 Prerequisite 时,以上 XPath 工作正常,但每当出现以上三个中的任何内容时,XPath 都会失败并给我整个文本。

有没有办法在 XPath 中放置多个分隔符?或者我该如何解决?

示例页面:

并存条件 URL:http://catalog.fullerton.edu/ajax/preview_course.php?catoid=16&coid=96106&show

先决条件 URL:http://catalog.fullerton.edu/ajax/preview_course.php?catoid=16&coid=96564&show

两者:http://catalog.fullerton.edu/ajax/preview_course.php?catoid=16&coid=98590&show

[旧线程] -

这段代码可以解决您的问题,除非您特别需要 XPath,我还建议您查看 BeautifulSoup 文档,了解我使用的方法,你可以发现 HERE

.next_element.next_sibling 在这些情况下非常有用。 或者 .next_elements 我们将得到一个生成器,我们必须以我们可以操纵生成器的方式转换或使用它。

from bs4 import BeautifulSoup
import requests


url = 'http://catalog.fullerton.edu/ajax/preview_course.php?catoid=16&coid=96564&show'
makereq = requests.get(url).text

soup = BeautifulSoup(makereq, 'lxml')

whole = soup.find('td', {'class': 'custompad_10'})
# we select the whole table (td), not needed in this case
thedivs = whole.find_all('div')
# list of all divs and elements within them

title_h3 = thedivs[2]
# we select only yhe second one (list) and save it in a var

mytitle = title_h3.h3
# using .h3 we can traverse (go to the child <h3> element)

mylist = list(mytitle.next_elements)
# title_h3.h3 is still part of a three and we save all the neighbor elements 

the_text = mylist[3]
# we can then select specific elements 
# from a generator that we've converted into a list (i.e. list(...))

prequisite = mylist[6]

which_cpsc = mylist[8]

other_text = mylist[11]

print(the_text, ' is the text')
print(which_cpsc, other_text, ' is the cpsc and othertext ')
# this is for testing purposes

解决了这两个问题,我们不必使用 CSS 选择器 和那些奇怪的列表操作。一切都是 organic 并且 works 很好。