python - 从网页中抓取特定文本

标签 python regex python-3.x web-scraping beautifulsoup

我目前正在尝试从网页上抓取一些图表,但我对此很陌生,不知道最好的解决方案。

<font color="DarkBLUE">
g:=Graph&lt;5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }&gt;;</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&lt;5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }&gt;;</font>

<font color="DarkBLUE">h:=Other&lt;...&gt;;</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&lt;5|{ {2, 3}, {4, 5}, {1, 3}, {1, 2}, {1, 5}, {1, 4}, {2, 4}, {3, 5}, {2,
5}, {3, 4} }&gt;;</font>

<font color="DarkBLUE">h:=Other&lt;...&gt;;</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/

相关文章:

python - 在 MacBook 上安装 pyspark

python - 在 Django 模型字段中存储位置历史记录

python - Tensorflow variable_scope 中的 partitioner 参数有什么用?

javascript - 正则表达式替换字符串的一部分

python - 如何根据引号在csv中写入值并忽略引号内的逗号?

python - 一起运行两个 Python 应用程序?

python - 有没有更好的方法在Python中读取多个txt文件?

ruby - gsub 部分替换

python - 如何使用正则表达式将特定的子字符串提取到新行中?

python - python套接字模块中未定义的名称错误