【发布时间】:2020-06-16 12:32:30
【问题描述】:
以下代码在计算机上运行以从 Instagram 帐户中抓取数据。 当我尝试在 VPS 服务器上使用它时,我被重定向到 Instagram 登录页面,因此脚本不起作用。
为什么当我在电脑或服务器上时,Instagram 的反应不同?
wget 也是一样。在计算机上我有个人资料页面,在服务器上我被重定向到登录页面。
import requests
import re
class InstagramScraper:
"""
Scraper of Instagram profiles infos.
"""
def __init__(self, session: requests.Session, instagram_account_name: str):
self.session = session
self._account_name = self.clean_account_name(instagram_account_name)
self.load_data()
def load_data(self):
#print(self._account_name)
response = self.session.get("https://www.instagram.com/{account_name}/".format(account_name=self._account_name))
#print(response)
#print(response.text)
publications_regex = r'"edge_owner_to_timeline_media":{"count":(\d*),'
self._publications = re.search(publications_regex, response.text).group(1)
followers_regex = r'"edge_followed_by":{"count":(\d*)'
self._followers = re.search(followers_regex, response.text).group(1)
# title_regex = r'"@type":".*","name":"(.*)",'
title_regex = r'"full_name":"(.*)",'
self._title = re.search(title_regex, response.text).group(1)
self._title = self._title.split('\"')[0]
following_regex = r'"edge_follow":{"count":(\d*)}'
self._following = re.search(following_regex, response.text).group(1)
def clean_account_name(self, value) -> str:
"""
Return the account name without the url address.
"""
found: str = re.search("https://www.instagram.com/(.*)/", value)
if found:
return found.group(1)
return value
@property
def publications(self) -> int:
"""
Number of publications by this account.
"""
return self._publications
@property
def followers(self) -> int:
"""
Number of followers of this account.
"""
return self._followers
@property
def title(self) -> str:
"""
Name of the Instagram profile.
"""
return self._title
@property
def account(self) -> str:
"""
Account name used on Instagram.
"""
return self._account_name
@property
def following(self) -> int:
"""
Number of accounts this profile is following.
"""
return self._following
def __str__(self) -> str:
return str({
'Account': self.account,
'Followers': self.followers,
'Publications': self.publications,
'Following': self.following,
'Title': self.title,
})
if __name__ == "__main__":
with requests.session() as session:
scraper = InstagramScraper(session, "https://www.instagram.com/ksc_lokeren/")
print(scraper)
【问题讨论】:
-
一些门户网站有复杂的系统来阻止机器人、爬虫、黑客、垃圾邮件发送者。最简单的方法是列出不受信任的 IP - 黑名单。但是您无法检查您的 IP 是否在此列表中。
标签: python web-scraping instagram wget