【问题标题】:How can I get certain text from a website with Python?如何使用 Python 从网站获取某些文本?
【发布时间】:2014-04-05 12:27:25
【问题描述】:

我正在使用 python 脚本从网站 (http://www.opensiteexplorer.org/) 获取特定文本。例如尝试这个搜索:http://www.opensiteexplorer.org/links?site=www.google.com

我想获得“页面授权”和“根域”并将它们过滤掉。我正在使用 lxml。

我正在使用此代码:

response = br.open( 'http://www.opensiteexplorer.org/links?site=' + blog)
tree = html.fromstring(response.read())
authority = int (tree.xpath('//span[@class="metrics-authority"]/text()')[1].strip())
if authority>1:
    print blog
    print 'This blog is ready to be registered'
    print authority
    f.write(blog +' '+ str(authority) +'\n')

我在这里过滤大于 1 的 PA,我还想过滤大于 5 的链接根域。我该怎么做?

【问题讨论】:

  • x/text() 在 XPath 中几乎总是一个坏主意:更喜欢 string(x)
  • 第四个div.has-tooltip中不是“根域”信息吗?
  • @larsmans 感谢您提供的信息。我真的是python的新手,我不知道。那么你能给我举个例子来说明这将如何实现吗?我猜是这样的:authority = tree.xpath('string(class="metrics-authority")')[1].strip()
  • @Fury 例如,如果你搜索 [opensiteexplorer.org/links?site=www.google.com] 我喜欢从那里刮掉 680k 的数字。我怎样才能得到它?

标签: python html xpath web-scraping lxml


【解决方案1】:

您可以使用 metrics-authority 类获得所有 2 个跨度,第一个是 Domain Authority,第二个是 Page Authority。此外,您可以从divid="metrics-page-link-metrics" 获得Root Domains

import urllib2
from lxml import html

tree = html.parse(urllib2.urlopen('http://www.opensiteexplorer.org/links?site=www.google.com'))

spans = tree.xpath('//span[@class="metrics-authority"]')
data = [item.text.strip() for item in spans]
print "Domain Authority: {0}, Page Authority: {1}".format(*data)

div = tree.xpath('//div[@id="metrics-page-link-metrics"]//div[@class="has-tooltip"]')[1]
print "Root Domains: {0}".format(div.text.strip())

打印:

Domain Authority: 100, Page Authority: 97 
Root Domains: 680

希望对您有所帮助。

【讨论】:

  • 感谢您的代码,但在这种情况下,我真正需要的是根域而不是域权限。
  • 感谢@alecxe 提供的信息,它真的很有用,但我已经更新了我的代码。刚才我想在 2 个变量中包含 PA 和根域,但首先要过滤它们。我需要 PA>1 和根域>5。我不需要 DA 指标。
  • @alexgarciab 这改变了游戏规则。对问题提出单独的问题,而不是更新现有问题。谢谢。
  • 我想在这里发布重复的内容不是一个好主意@alecxe - 我只想知道如何提取这些值并将它们存储在变量中。
猜你喜欢
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 2016-04-18
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
相关资源
最近更新 更多