Python WebScraper未更新

时间:2017-05-01 22:02:25

标签: python web-scraping

大家好,所以我创建了一个简单的网络抓取工具,在搜索隐私后,会从cnet的头条新闻中获取相关文章和日期。如我的代码中所示,它用于提取数据的链接,但我遇到了问题。无论我添加到网址代码末尾的页码,它只是抓取第一页。我已经使用其他网址测试了它,它会提取不同的数据,所以我不明白为什么当我更改网址末尾的页码时,它没有与该网页相关的特定数据。

如果可能的话我试图让它从所有页面中提取数据,但是现在我正试图让它与至少一个不同的页面一起使用,而不是在搜索"隐私&时返回的主页面。 #34;

下面是python代码

import urllib.request,re,webbrowser

##import MySQLdb
import cgi




##getUrl =
##getDate =
##getHeadline =
##
##cursor.execute(SQL)

def searchurl(url):

    page=urllib.request.urlopen(url)
    urls=page.read().decode(errors='replace')
    page.close()
    print("Searching:",url)
    ##get headers

    head = re.findall('(?<=<h3>).+?(?=</h3>)',urls)
    ##get links
    link = re.findall('(?<= <a href="/).+?\S+?(?=">)',urls,re.DOTALL)


    ##get date
    date = re.findall('(?<= <span class="assetTime">).+?(?=</span>)',urls)




    link.pop(0)
    link.pop(0)
    link.pop(0)
    link.pop(-1)
    link.pop(-1)
    for item in link:
        print(item)
    print("Header")
    for item in head:
        print(item)








url = "https://www.cnet.com/search/?query=privacy&page=3"
searchurl(url)

以下是shell输出

Searching: https://www.cnet.com/search/?query=privacy&page=3
news/the-circle-review-tom-hanks-emma-watson-tech-dave-eggers/
products/avg-privacy-glasses/preview/
news/amazon-reveals-its-newest-device-the-echo-look/
news/unroll-me-hit-with-privacy-suit-over-alleged-sale-of-user-data/
videos/tim-cook-almost-put-the-brakes-on-uber-over-privacy/
news/pause-pod-kickstarter-privacy-tent/
news/privacy-browser-brave-tor-trump/
news/microsoft-wants-you-to-trust-windows-10-privacy-again/
videos/what-is-vpn-explained-privacy-guide/
news/trump-signs-bill-repealing-us-internet-privacy-rules/
Header
'The Circle': A movie review for the tech literate
AVG Privacy Glasses
Amazon reveals the Echo Look, a device for style selfies
Unroll.me hit with privacy suit over alleged sale of user data
Tim Cook almost put the brakes on Uber over privacy
Hide from the world with your own pop-up privacy tent
Want true privacy? You need to check out this browser
Microsoft is fixing those confusing Windows 10 privacy messages
VPN explained: A privacy primer -- with robots and race cars
Trump signs bill repealing US internet privacy rules

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以直接通过浏览器导航确认上述网址不会重定向到正确的网页。浏览器中的https://www.cnet.com/search/?query=privacy&page=6会将您带到第1页。

通过查看页面选择器等,您可以看到分页的工作原理如下: <a class="pageno" data-pageno="2" href="/search/?query=privacy&amp;fq=&amp;sort=1&amp;p=2&amp;typeName=&amp;rpp=10">2</a>

(例如,您可以使用Google Chrome中的&#34; Inspect&#34;工具查看此内容。)

将此更新的端点添加到URL将允许我们以编程方式指定页面。例如,要转到第6页,请使用:

https://www.cnet.com/search/?query=privacy&fq=&sort=1&p=6&typeName=&rpp=10

更新代码以使用此网址(指定&p=6部分中的页面)应该可以解决问题。