可以通过以下步骤实现:
from bs4 import BeautifulSoup
import requests
url = "网页的URL地址"
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
h2_tags = soup.find_all('h2')
target_text = ""
for i in range(len(h2_tags)):
if h2_tags[i].text == "目标h2标签的文本":
target_text = h2_tags[i+1].text
break
完整的代码示例:
from bs4 import BeautifulSoup
import requests
url = "网页的URL地址"
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
h2_tags = soup.find_all('h2')
target_text = ""
for i in range(len(h2_tags)):
if h2_tags[i].text == "目标h2标签的文本":
target_text = h2_tags[i+1].text
break
print(target_text)
这样就可以获取到目标h2标签之间的文本内容了。
注意:以上代码中的"网页的URL地址"需要替换为实际的网页URL地址,"目标h2标签的文本"需要替换为实际的目标h2标签的文本。
领取专属 10元无门槛券
手把手带您无忧上云