如何Webscraping Instagram个人资料链接BeautifulSoup?

时间:2019-01-30 16:32:41

标签: python beautifulsoup instagram instagram-api

我才刚刚开始学习如何使用BeautifulSoup进行网络抓取,并想编写一个简单的程序,该程序将通过Instagram中的FullName获取我的偶像的个人资料链接(instagram网址)。

示例:我在文件fullname.txt中存储了FullName列表,如下所示:

#cat fullname.txt
Cristiano Ronaldo
David Beckham
Michael Jackson

我的结果愿望是:

https://www.instagram.com/cristiano/
https://www.instagram.com/davidbeckham/
https://www.instagram.com/michaeljackson/

能给我一些建议吗?

1 个答案:

答案 0 :(得分:3)

这适用于所有3个名称,另外一些我添加到fullname.txt

它使用请求库和Bing搜索来查找正确的链接,然后使用正则表达式从返回的数据包中解析出该链接。


import requests, re

def bingsearch(searchfor):

    link = 'https://www.bing.com/search?q={}&ia=web'.format(searchfor)

    ua = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36'}

    payload = {'q': searchfor}

    response = requests.get(link, headers=ua, params=payload)               

    try:
        found = re.search('Search Results(.+?)</a>', response.text).group(1)

        iglink = re.search('a href="(.+?)"', found).group(1)

    except AttributeError:
        iglink = "link not found"

    return iglink


with open("fullname.txt", "r") as f:
    names = f.readlines()

for name in names:
    name = name.strip().replace(" ", "+")

    searchterm = name + "+instagram"

    IGLink = bingsearch(searchterm)

    print(IGLink)