我目前正在尝试从网页上抓取一些图表,但我对此很陌生,不知道最好的解决方案。
<font color="DarkBLUE">
g:=Graph<5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }>;</font>
我需要的是g:=Graph<..>
部分。
这是我到目前为止所尝试的(基于其他一些类似的问题):
tree = lh.fromstring(data)
rate = tree.xpath("//font[@color='DarkBLUE']")
graphurls.append(rate[0].text_content())
但问题是它还刮掉了很多其他东西。我认为这是可以做到的,因为它有一个独特的模式g:=Graph<...>
所以没有其他东西被刮掉。
你能帮我吗?
最佳答案
第一种方法:你有字符串,所以你可以使用字符串的函数来过滤结果 - 即。
if text.strip().startswith('g:=Graph') :
示例:
data = '''<font color="DarkBLUE">
g:=Graph<5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }>;</font>
<font color="DarkBLUE">h:=Other<...>;</font>'''
import lxml.html as lh
tree = lh.fromstring(data)
rate = tree.xpath("//font[@color='DarkBLUE']")
for item in rate:
text = item.text_content()
text = text.strip()
if text.startswith('g:=Graph'):
print(' OK:', text)
else:
print('NOT:', text)
第二种方法:可以使用xpath
来过滤
tree.xpath("//font[@color='DarkBLUE' and contains(text(), 'g:=Graph')]")
或
tree.xpath("//font[@color='DarkBLUE'][contains(text(), 'g:=Graph')]")
示例:
data = '''<font color="DarkBLUE">
g:=Graph<5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }>;</font>
<font color="DarkBLUE">h:=Other<...>;</font>'''
import lxml.html as lh
tree = lh.fromstring(data)
rate = tree.xpath("//font[@color='DarkBLUE' and contains(text(), 'g:=Graph')]")
for item in rate:
text = item.text_content()
text = text.strip()
print(text)
最终使用 starts-with()
但数据中的文本位于新行中,因此 xpath 中的文本在开始时需要 \n
tree.xpath("//font[@color='DarkBLUE' and starts-with(text(), '\ng:=Graph')]")
顺便说一句: xpath cheatsheet
关于python - 从网页中抓取特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60531642/