漂亮的刮汤器查找文本
Beautiful soup scraper find text
from bs4 import BeautifulSoup
from lxml import etree
import requests
import re
URL = "https://csimarket.com/stocks/at_glance.php?code=AA"
HEADERS = ({'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36', \
'Accept-Language': 'en-US, en;q=0.5'})
webpage = requests.get(URL, headers=HEADERS)
soup = BeautifulSoup(webpage.content, "html.parser")
dom = etree.HTML(str(soup))
raw_html = soup.find('a', href="../Industry/Industry_Data.php?s=100")
print(raw_html)
我得到:
\<span class="oran2"\>•\</span\>Basic Materials
我只想“基础材料”我该怎么做?
我在做:
raw_html = soup.find('a', href="../Industry/Industry_Data.php?s=100")
我只想找到 ../Industry/Industry_Data.php
。谢谢
当你这样做时
raw_html = soup.find('a', href="../Industry/Industry_Data.php?s=100")
你得到了整个标签作为函数的结果。目前它包含文本以及具有项目符号点字符的跨度。
因此,要仅获取文本(“基本材料”),您需要从元素中删除跨度。您可以通过在 span 上使用 .decompose()
(或您通常要删除的任何元素)来执行此操作。
之后可以使用.text
属性获取a
标签的内部文本。
PS:.text
包含空格,因此建议使用 .strip()
。
代码:
span = a_tag.find("span")
span.decompose()
print(a_tag.text.strip())
输出:
Basic Materials
from bs4 import BeautifulSoup
from lxml import etree
import requests
import re
URL = "https://csimarket.com/stocks/at_glance.php?code=AA"
HEADERS = ({'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36', \
'Accept-Language': 'en-US, en;q=0.5'})
webpage = requests.get(URL, headers=HEADERS)
soup = BeautifulSoup(webpage.content, "html.parser")
dom = etree.HTML(str(soup))
raw_html = soup.find('a', href="../Industry/Industry_Data.php?s=100")
print(raw_html)
我得到:
\<span class="oran2"\>•\</span\>Basic Materials
我只想“基础材料”我该怎么做?
我在做:
raw_html = soup.find('a', href="../Industry/Industry_Data.php?s=100")
我只想找到 ../Industry/Industry_Data.php
。谢谢
当你这样做时
raw_html = soup.find('a', href="../Industry/Industry_Data.php?s=100")
你得到了整个标签作为函数的结果。目前它包含文本以及具有项目符号点字符的跨度。
因此,要仅获取文本(“基本材料”),您需要从元素中删除跨度。您可以通过在 span 上使用 .decompose()
(或您通常要删除的任何元素)来执行此操作。
之后可以使用.text
属性获取a
标签的内部文本。
PS:.text
包含空格,因此建议使用 .strip()
。
代码:
span = a_tag.find("span")
span.decompose()
print(a_tag.text.strip())
输出:
Basic Materials